'Bind request method POST

I have a problem with binding my request, because there are a lot of parameters, so I used struct containing param.

package api
import (
    "github.com/labstack/echo/v4"
    "net/http"
    "trains-api/domain/models"
    "trains-api/domain/services"
)

type reqCreate struct {
    RequestNotifi  models.ResquestCreateNotifi  
}
func CreateNotification (c echo.Context) error {
    req := reqCreate{}

    if err := c.Bind(req); err != nil {
        return c.JSON(http.StatusNotFound, err)
    }
}
package models

type RequestCreateNotifi struct {
    Name_param1     string    `db:"Name_param1"`
    Name_param2     string    `db:"Name_param2"`
    ....
    Name_param_n    string    `db:"Name_paramN"`
}

error at if err := c.Bind(req); err != nil

r = {interface {} | string } "reflect: Elem of invalid type"


Solution 1:[1]

You need to set the JSON equivalent of each field in the model like so:

package models
type RequestCreateNotifi struct {
    Name_param1     string    `json:"name_param1" db:"Name_param1"`
    Name_param2     string    `json:"name_param2" db:"Name_param2"`
    ....
    Name_param_n    string    `json:"name_param_n" db:"Name_param n"`
}

This json field specifies how the field is represented in the request so it can bind it to the correct value.

Solution 2:[2]

You need to add the pointer

req := reqCreate{}

if err := c.Bind(&req); err != nil {
    return c.JSON(http.StatusNotFound, err)
}

Solution 3:[3]

Unfortunately you can't bind automatically query parameter using Post methode for security reasons according to issue#1670, the way to do it is using echo.QueryParamsBinder

type Query struct {
Param1 string `query:"param1"`
Param2 string `query:"param2"`
}

...
query := new(Query)
err := echo.QueryParamsBinder(ctx).String("param1", &query.Param1).String("param2", &query.Param2).BindError()
...
 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 v4570
Solution 2 Nankai
Solution 3 MoadKey