Home > Mobile >  How to add optional parameter for echo.Bind?
How to add optional parameter for echo.Bind?

Time:06-02

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.

CodePudding user response:

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}

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related