英文:
Golang - Binding Headers in echo api
问题
Golang - 在 echo API 中绑定请求头
我正在尝试将请求头绑定到结构体中。到目前为止,我按照文档中的示例进行了相同的操作(这里),但似乎根本不起作用。我在调试器中检查了传入的请求,它具有正确的头部名称和值,但 echo 没有进行绑定。
这是我的 API 代码:
package main
import (
"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"
英文:
Golang - Binding Headers in echo api
I'm trying to bind headers to struct. So far I did the same as in documentation here but it looks like doesn't work at all. I checked in debugger incoming request and it has proper header name and value but echo doesn't bind it.
Here is my api:
package main
import (
"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")
}
and my request
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
得分: 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")
}
英文:
See this answer.
Tried this code and it works:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论