1

我的请求绑定有问题,因为参数很多,所以我使用了包含param的struct。

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

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

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

2 回答 2

1

您需要设置模型中每个字段的 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 字段指定该字段在请求中的表示方式,以便它可以将其绑定到正确的值。

于 2019-11-15T13:39:26.173 回答
1

您需要添加指针

req := reqCreate{}

if err := c.Bind(&req); err != nil {
    return c.JSON(http.StatusNotFound, err)
}
于 2022-01-15T18:58:29.847 回答