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 回答
![?](http://img1.sycdn.imooc.com/54584d6100015f5802200220-100-100.jpg)
繁星点点滴滴
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")
}
- 1 回答
- 0 关注
- 72 浏览
添加回答
举报
0/150
提交
取消