1

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"
Andy
  • 449
  • 5
  • 13
Doctor Strange
  • 37
  • 1
  • 2
  • 10

3 Answers3

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.

v4570
  • 490
  • 1
  • 3
  • 14
1

You need to add the pointer

req := reqCreate{}

if err := c.Bind(&req); err != nil {
    return c.JSON(http.StatusNotFound, err)
}
Nankai
  • 931
  • 9
  • 21
1

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()
...
 
Moad Meftah
  • 211
  • 3
  • 7