How to add optional parameter for echo.Bind?

Issue

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.

Solution

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}

Answered By – spike014

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.