這是我的代碼
ABC:= model.ABC{}
if err := c.Bind(&ABC); err != nil {}
c是 echo.Context
這是我的模型:
type ABC struct {
Name string `json:"name"`
Age int `json:"int"`
}
我想要Age可選的。所以當我沒有在正文請求中傳遞它時。它仍然有效。
uj5u.com熱心網友回復:
你可以試試:
type ABC struct {
Name string `json:"name"`
Age *int `json:"int"`
}
并記住在使用Age欄位之前檢查它:
a := ABC{}
// ...
if a.Age != nil {
// Do something you want with `Age` field
}
這是我對這個問題的演示:
package main
import (
"net/http"
"github.com/labstack/echo/v4"
)
type User struct {
Name string `json:"name"`
Email *int `json:"email"`
}
func main() {
e := echo.New()
e.POST("/", func(c echo.Context) error {
// return c.String(http.StatusOK, "Hello, World!")
u := new(User)
if err := c.Bind(u); err != nil {
return err
}
return c.JSON(http.StatusOK, u)
})
e.Logger.Fatal(e.Start(":1323"))
}
go run main.go
? curl -X POST http://localhost:1323 \
-H 'Content-Type: application/json' \
-d '{"name":"Joe"}'
{"name":"Joe","email":null}
? curl -X POST http://localhost:1323 \
-H 'Content-Type: application/json' \
-d '{"name":"Joe", "email": 11}'
{"name":"Joe","email":11}
uj5u.com熱心網友回復:
不幸的是,Go 不支持開箱即用的可選引數。我看到你正在使用 Gin,你可以使用
abc := ABC{}
if body, err := c.GetRawData(); err == nil {
json.Unmarshal(body, abc)
}
這會將請求中未傳遞的欄位的值設定為零值。然后,您可以繼續將值設定為所需的任何值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/485170.html
標籤:去
上一篇:將變數限制為自身和其他特定包
