如何为 echo.Bind 添加可选参数?

How to add optional parameter for echo.Bind?

这是我的代码

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 选项。所以当我不在正文请求中传递它时。它仍然有效。

不幸的是,Go 不支持开箱即用的可选参数。我看到你正在使用 Gin,你可以使用

abc := ABC{}
if body, err := c.GetRawData(); err == nil {
        json.Unmarshal(body, abc)
}

这会将请求中未传递的字段的值设置为零值。然后您可以继续将值设置为所需的值。

你可以试试:

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}