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

为什么没有读取标头值?

为什么没有读取标头值?

Go
catspeake 2022-10-04 16:22:48
package middlewareimport ("fmt""github.com/labstack/echo/v4")type _getData struct {Token string `header:"Authorization"`}func TokenCheck(next echo.HandlerFunc) echo.HandlerFunc {return func(c echo.Context) error {    a := new(_getData)    c.Bind(a)    fmt.Print(a)    return next(c)}}标头中有一个自治值,使用绑定到回声框架,我想知道授权值,但没有返回值。
查看完整描述

1 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

BindHeaders未被调用 。源代码:Bind


func (b *DefaultBinder) Bind(i interface{}, c Context) (err error) {

    if err := b.BindPathParams(c, i); err != nil {

        return err

    }

    // Issue #1670 - Query params are binded only for GET/DELETE and NOT for usual request with body (POST/PUT/PATCH)

    // Reasoning here is that parameters in query and bind destination struct could have UNEXPECTED matches and results due that.

    // i.e. is `&id=1&lang=en` from URL same as `{"id":100,"lang":"de"}` request body and which one should have priority when binding.

    // This HTTP method check restores pre v4.1.11 behavior and avoids different problems when query is mixed with body

    if c.Request().Method == http.MethodGet || c.Request().Method == http.MethodDelete {

        if err = b.BindQueryParams(c, i); err != nil {

            return err

        }

    }

    return b.BindBody(c, i)

}

您可以通过以下方式获取标头中的值:


func TokenCheck(next echo.HandlerFunc) echo.HandlerFunc {

    b := &echo.DefaultBinder{}

    return func(c echo.Context) error {

        a := new(_getData)

        b.BindHeaders(c, a)

        fmt.Print(a)

        return next(c)

    }

}

艺术


token := c.Request().Header.Get("Authorization")


查看完整回答
反对 回复 2022-10-04
  • 1 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

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