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

huangapple go评论82阅读模式
英文:

How to add optional parameter for echo.Bind?

问题

这是我的代码:

ABC := model.ABC{}
if err := c.Bind(&ABC); err != nil {}

cecho.Context

这是我的模型:

type ABC struct {
    Name string `json:"name"`
    Age  int    `json:"int,omitempty"`
}

我想让 Age 字段是可选的。所以当我在请求体中不传递它时,它仍然可以正常工作。

英文:

Here is my code

ABC:= model.ABC{}
if err := c.Bind(&ABC); err != nil {}

c is echo.Context

Here is my model:

type ABC struct {
    Name string `json:"name"`
    Age  int    `json:"int"`
}

I want the Age optional. So when I do not pass it in the body request. It still works.

答案1

得分: 4

你可以尝试以下代码:

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}
英文:

You can try:

type ABC struct {
    Name string  `json:"name"`
    Age  *int    `json:"int"`
}

And remember check it before you use Age field:

a := ABC{}

// ...

if a.Age != nil {
 // Do something you want with `Age` field
}

Here is my demo for this question:

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}

答案2

得分: 1

很抱歉,Go语言默认不支持可选参数。我看到你正在使用Gin框架,你可以使用以下代码:

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

这将把请求中未传递的字段的值设置为零值。然后,你可以根据需要设置这些字段的值。

英文:

Unfortunately, Go does not support optional parameters out of the box. I see that you are using Gin, you can use

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

This will set the value of the fields not passed in the request to zero values. You can then proceed to set the values to whatever is required.

huangapple
  • 本文由 发表于 2022年6月1日 16:32:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/72458686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定