1 回答

TA貢獻1827條經(jīng)驗 獲得超4個贊
render.Bind僅輸入,即用于解碼請求有效負(fù)載。而是用于render.JSON發(fā)送 json 響應(yīng)。
func GetOrderByIdHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
orderId := chi.URLParam(r, "orderId")
order, err := fetchOrder(orderId)
if err != nil {
render.Render(w, r, NewInternalServerError(err))
return
}
log.Info("order status is " + order.Status)
render.JSON(w, r, order)
}
}
或者,您也可以使用標(biāo)準(zhǔn)方法:導(dǎo)入encoding/json包,然后像這樣使用它:
func GetOrderByIdHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
orderId := chi.URLParam(r, "orderId")
order, err := fetchOrder(orderId)
if err != nil {
render.Render(w, r, NewInternalServerError(err))
return
}
log.Info("order status is " + order.Status)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(order); err != nil {
render.Render(w, r, NewInternalServerError(err))
}
}
}
另請注意,多個結(jié)構(gòu)標(biāo)記的正確格式是“空格分隔”而不是“逗號分隔”。例如:json:"quantity" gorm:"not null"是正確的,而json:"quantity",gorm:"not null"不是。
- 1 回答
- 0 關(guān)注
- 125 瀏覽
添加回答
舉報