go - 绑定(bind)请求方式POST

标签 go struct go-echo

我在绑定(bind)请求时遇到问题,因为参数很多,所以我使用了包含参数的结构。

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);错误!=零

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

最佳答案

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

关于go - 绑定(bind)请求方式POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58870408/

相关文章:

go - 编写 CLI : How to avoid showing the typed password on screen

docker - '/bin/sh : go: not found' in 'docker:dind' container

c - 音频数据包类型

ios - 在 Swift 中接受多种结构类型的函数

c - 在 C 中初始化包含函数指针的结构

json - 使用 Echo 测试 POST 请求(预期输出与实际输出)

amazon-web-services - 如何将 GO Echo 我的应用程序部署到 Elastic Beanstalk

validation - Go - 用于验证的数据类型

struct - golang 从结构中返回第一个字段