golang实现get,post请求,传送json数据

golang实现get,post请求,传送json数据,第1张

package main

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"time"
)

func main() {
	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", Index)
	router.HandleFunc("/todos", TodoIndex)
	//curl  -H "Content-Type:application/json" -X GET  -i  'http://127.0.0.1:8080/todos/123/zgx'
	router.HandleFunc("/todos/{todoId}/{name}", TodoShow)
	
	//curl  -H "Content-Type:application/json" -X POST -d '{"name":"zgx","age":30}'  -i  'http://127.0.0.1:8080/handlePostJson' 
	router.HandleFunc("/handlePostJson", handlePostJson)

	log.Fatal(http.ListenAndServe(":8080", router))
}

func handlePostJson(w http.ResponseWriter, r *http.Request) {
	decoder:=json.NewDecoder(r.Body)
	var params map[string]interface{}
	decoder.Decode(¶ms)
	fmt.Println("POST json req: ",params)
	fmt.Fprintln(w,`{"code":0,"msg":"succ"}`)
}

func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Welcome!")
}

func TodoIndex(w http.ResponseWriter, r *http.Request) {
	//params:= r.URL.Query()
	//username:= params.Get("username")
	//fmt.Println("request: ",username)

	servicetype := r.PostFormValue("servicetype")
	fmt.Println("request: ", servicetype)

	fmt.Fprintln(w, "Todo Index!")
	type Todos []Todo
	todos := Todos{
		Todo{Name: "Write presentation"},
		Todo{Name: "Host meetup"},
	}
	if err := json.NewEncoder(w).Encode(todos); err != nil {
		panic(err)
	}
}

type Todo struct {
	Name      string    `json:"name"`
	Completed bool      `json:"completed"`
	Due       time.Time `json:"due"`
}

func TodoShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	todoId := vars["todoId"]
	name := vars["name"]
	fmt.Println("request: ", vars)
	fmt.Fprintln(w, "response: Id:", todoId, "name:", name)
}

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/996233.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存