绑定请求方法POST

时间:2019-11-15 04:37:24

标签: go struct go-echo

我绑定请求时遇到问题,因为param很多,所以我使用struct contains 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_param n"`
}

if err := c.Bind(req); err != nil处的错误

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

1 个答案:

答案 0 :(得分:0)

您需要像这样设置模型中每个字段的JSON等效项:

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"`
}

此json字段指定该字段在请求中的表示方式,以便可以将其绑定到正确的值。