go - 如何将数据从中间件传递到处理程序?

标签 go

我正在设计我的处理程序以返回 http.Handler。这是我的处理程序的设计:

 func Handler() http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  })
}

我的中间件设计为接受一个 http.Handler,然后在中间件完成其操作后调用该处理程序。这是我的中间件的设计:

 func Middleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // Middleware operations

    next.ServeHTTP(w, r)
  })
}

考虑到我的中间件和处理程序的设计,将信息从中间件传递到处理程序的正确方法是什么?我试图从我的中间件传递给处理程序的信息是从请求正文解析的 JSON Web token 。如果我没有将解析的 JWT 传递给处理程序,那么我将需要在我的处理程序中再次解析 JWT。在中间件和处理程序中解析 JWT 的请求正文似乎很浪费。以防万一这些信息是相关的,我将标准的 net/http 库与 gorilla mux 一起使用。

最佳答案

既然您已经在使用 Gorilla看看context包。

(如果您不想更改方法签名,这很好。)

import (
    "github.com/gorilla/context"
)

...

func Middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Middleware operations
        // Parse body/get token.
        context.Set(r, "token", token)

        next.ServeHTTP(w, r)
    })
}

...

func Handler() http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := context.Get(r, "token")
    })
}

更新

Gorilla context 包现在处于维护模式
每个 repo :

Note gorilla/context, having been born well before context.Context existed, does not play well with the shallow copying of the request that http.Request.WithContext (added to net/http Go 1.7 onwards) performs.

Using gorilla/context may lead to memory leaks under those conditions, as the pointers to each http.Request become "islanded" and will not be cleaned up when the response is sent.

You should use the http.Request.Context() feature in Go 1.7.

关于go - 如何将数据从中间件传递到处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31504456/

相关文章:

windows - 在 Go 和 Windows API 中处理未确定大小的数组

Go - 如何按照 go-ui 的指示安装包

google-app-engine - GO项目的Appengine文件夹结构

go - 提取 avro 架构

amazon-web-services - AWS网关响应未传回401未经授权的授权者上下文

xml - 如何从 marshal 重新排序 xml 标签

pointers - 如何使用反射读取指向 slice 的指针的值?

go - 在 C 和 Golang 中共享结构定义的最佳方式是什么

http - 在 Go 中返回一个值而不是一个指针

mongodb - 用MongoDB官方Golang驱动可以查到一条记录,但是记录是空的