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")
}
- 1 回答
- 0 關注
- 100 瀏覽
添加回答
舉報
0/150
提交
取消