登录
首页 >  Golang >  Go问答

将参数从中间件传递到下一个句柄函数

来源:stackoverflow

时间:2024-04-08 12:00:35 114浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《将参数从中间件传递到下一个句柄函数》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我想制作一个可重用的中间件,用于在我的 api 中进行验证。在这里,验证是通过 govalidator 完成的,因此我只需要传递验证规则和请求映射到的 dto。

func validationmiddleware(next http.handlerfunc, validationrules govalidator.mapdata, dto interface{}) http.handlerfunc {
    return func(rw http.responsewriter, r *http.request) {
        utils.setresponseheaders(rw)
        opts := govalidator.options{
            request:         r,
            data:            &dto,
            rules:           validationrules,
            requireddefault: true,
        }

        v := govalidator.new(opts)
        err := v.validatejson()

        if err != nil {
            fmt.println("middleware found an error")
            err := utils.errorwrapper{
                statuscode: 400,
                type:       "bad request",
                message:    err,
            }
            err.throwerror(rw)
            return
        }
        next(rw, r)
    }
}

这就是 handlefunc 的样子:

var rules govalidator.MapData = govalidator.MapData{
    "name":        []string{"required"},
    "description": []string{"required"},
    "price":       []string{"required", "float"},
}

func RegisterItemsRouter(router *mux.Router) {
    itemsRouter := router.PathPrefix("/inventory").Subrouter()

    itemsRouter.HandleFunc("/", middleware.ValidationMiddleware(addItem, rules, dto.CreateItem{
        Name:        "",
        Description: "",
        Price:       govalidator.Float64{},
    })).Methods("POST")
}

如果没有发现错误,govalidator 会将请求正文解析到 dto 结构中,因此我想将其传递到下一个处理程序中,并避免再次尝试解析正文。

如何将此结构传递给下一个 handlefunc?


正确答案


从代码来看,您似乎将请求传递给验证器选项,验证器从中读取并验证正文。这会带来几个问题:http 请求只能读取一次,因此验证器要么以某种方式返回该未编组的对象,要么您必须在验证它之前读取正文。

对于第二种解决方案,第一件事是验证器必须知道它必须解组到的对象的类型:

func validationmiddleware(next http.handlerfunc, factory func() interface{}, validationrules govalidator.mapdata, dto interface{}) http.handlerfunc {
    return func(rw http.responsewriter, r *http.request) {
      newinstance:=factory()
      data, err:=ioutil.readall(r.body)
      json.unmarshal(data,newinstance)
      // validate newinstance here
      r.withcontext(context.withvalue(r.context(),"data",newinstance))
      next(wr,r)
   }
}

其中 func 工厂 是一个函数,用于创建将为请求解组的对象实例:

func registeritemsrouter(router *mux.router) {
    itemsrouter := router.pathprefix("/inventory").subrouter()

    itemsrouter.handlefunc("/", middleware.validationmiddleware(additem, func() interface{} { return &thestruct{}}, rules, dto.createitem{
        name:        "",
        description: "",
        price:       govalidator.float64{},
    })).methods("post")
}

这样,当新请求到来时,将创建 thestruct 的新实例并对其进行解组,然后进行验证。如果验证通过,它将被放入上下文中,以便下一个中间件或处理程序可以获取它:

func handler(wr http.ResponseWriter,r *http.Request) {
   item:=r.Context().Value("data").(*TheStruct)
   ...
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《将参数从中间件传递到下一个句柄函数》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>