1 回答

TA貢獻1735條經驗 獲得超5個贊
您可以為 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()
}
如果您的主體非常通用,您也可以解組為 map[string]interface{}。
試試
curl -XPOST -d '{"groups": [1]}' http://localhost:4000/foo
- 1 回答
- 0 關注
- 180 瀏覽
添加回答
舉報