3 回答

TA貢獻1783條經(jīng)驗 獲得超4個贊
GO 不同于 PHP 和 JS。它不是易于使用,而是專注于明確和可靠。
要在請求中解析 JSON 主體,我們應該有強類型結(jié)構(gòu)定義來描述接收有效負載的結(jié)構(gòu)。這就是我們?nèi)绾慰刂茟撝С值淖侄?。這很重要,因為每個文件都有自己的類型,如果來自請求的字符串與該類型不匹配,解析將失敗。
type RequestBody struct {
User User `json:"user"`
Profile Profile `json:"profile"`
}
type User struct {
UserName string `json:"username"`
Password string `json:"password"`
}
type Profile struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Files []string `json:"files"`
}
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var req RequestBody
err := decoder.Decode(&req)
if err != nil {
// log error and return 400 to caller
return
}
// Use req
}

TA貢獻1829條經(jīng)驗 獲得超4個贊
現(xiàn)在我使用這段代碼:
type Merchant struct{}
func (*Merchant) Register(context context.Context){
type registerRequestData struct{
Merchant models.MrtMerchant `json:"merchant"`
User models2.UsrUser `json:"user"`
Profile models2.UsrUserProfile `json:"profile"`
Branch models.MrtMerchantBranch `json:"branch"`
}
var request registerRequestData
if err:=context.ReadJSON(&request);err!=nil{
panic(err)
}
fmt.Printf("%+v\n",request)
}

TA貢獻1906條經(jīng)驗 獲得超10個贊
如果使用 iris 框架,你可以像這樣使用 ReadJSON 函數(shù):
func serve(context context.Context){
var request map[string]interface{}
context.ReadJSON(request)
username:=request["user"].(map[string]string)["username"]
fmt.Println(username)
}
- 3 回答
- 0 關(guān)注
- 204 瀏覽
添加回答
舉報