2 回答

TA貢獻1883條經驗 獲得超3個贊
你可以試試:
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}

TA貢獻1943條經驗 獲得超7個贊
不幸的是,Go 不支持開箱即用的可選參數。我看到你正在使用 Gin,你可以使用
abc := ABC{}
if body, err := c.GetRawData(); err == nil {
json.Unmarshal(body, abc)
}
這會將請求中未傳遞的字段的值設置為零值。然后您可以繼續將值設置為所需的值。
- 2 回答
- 0 關注
- 150 瀏覽
添加回答
舉報