在我的Go应用程序中,我有这样的路线:
router.HandleFunc(“/ api / users_groups_relationship / {user_id:[0-9] +}”,controllers.CreateUsersGroupsRelationship).Methods(“POST”)我发了POST请求。身体……
您可以为Request对象定义结构,然后将JSON解组到其中。
package main import ( "fmt" "github.com/gorilla/mux" "net/http" "encoding/json" ) //Request is our request body. type Request struct { Groups []int `json:"groups"` } //JsonTest1 is the http handler. func JsonTest1(w http.ResponseWriter, r *http.Request) { req := new(Request) //decode request to struct. if err := json.NewDecoder(r.Body).Decode(&req); err != nil{ w.WriteHeader(400) //bad request } w.WriteHeader(200) b, _ := json.Marshal(req) w.Write(b) w.Header().Set("Content-Type", "application/json; charset=utf-8") } func main(){ fmt.Printf("starting backend server\n") root := mux.NewRouter() root.HandleFunc("/foo", JsonTest1) webServer := &http.Server{Addr: ":4000", Handler: root} webServer.ListenAndServe() }
如果你的身体非常通用,你也可以解组来映射[string] interface {}。
试试吧
curl -XPOST -d '{"groups": [1]}' http://localhost:4000/foo