为了账号安全,请及时绑定邮箱和手机立即绑定

Golang - 在 echo api 中绑定标头

Golang - 在 echo api 中绑定标头

Go
千万里不及你 2023-01-03 10:15:18
Golang - 在 echo api 中绑定标头我正在尝试将标头绑定到结构。到目前为止,我所做的与此处的文档相同,但看起来根本不起作用。我检查了调试器传入请求,它具有正确的标头名称和值,但 echo 没有绑定它。这是我的 API:package mainimport (    "net/http"    "github.com/labstack/echo/v4")type User struct {    ID string `header:"Id"`}func handler(c echo.Context) error {    request := new(User)    if err := c.Bind(request); err != nil {        return c.String(http.StatusBadRequest, err.Error())    }    return c.String(http.StatusOK, "rankView")}func main() {    api := echo.New()    api.POST("product/rank/view", handler)    api.Start(":3000")}和我的要求curl -X POST "http://localhost:3000/product/rank/view" \     -H "accept: application/json" \     -H "Id: test" \     -H "Content-Type: application/x-www-form-urlencoded" -d "productId=123132"
查看完整描述

1 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

看到这个答案

试过这段代码,它有效:

package main


import (

        "fmt"

        "github.com/labstack/echo/v4"

        "net/http"

)


type User struct {

        ID string `header:"Id"`

}


func handler(c echo.Context) error {

        request := new(User)

        binder := &echo.DefaultBinder{}


        binder.BindHeaders(c, request)

        fmt.Printf("%+v\n", request)


        return c.String(http.StatusOK, "rankView")

}


func main() {

        api := echo.New()

        api.POST("product/rank/view", handler)

        api.Start(":3000")

}


查看完整回答
反对 回复 2023-01-03
  • 1 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信