【发布时间】:2017-02-18 04:26:21
【问题描述】:
我试图了解 Golang 1.7 中引入的上下文是如何工作的,以及将它传递给中间件和 HandlerFunc 的适当方法是什么。那么上下文是否应该在主函数中初始化并传递给checkAuth 函数?以及如何将其传递给Hanlder 和ServeHTTP 函数?
我读过Go concurrency patterns 和How to use Context,但我很难让这些模式适应我的代码。
func checkAuth(authToken string) util.Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Auth") != authToken {
util.SendError(w, "...", http.StatusForbidden, false)
return
}
h.ServeHTTP(w, r)
})
}
}
// Handler is a struct
type Handler struct {
...
...
}
// ServeHTTP is the handler response to an HTTP request
func (h *HandlerW) ServeHTTP(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
// decode request / context and get params
var p params
err := decoder.Decode(&p)
if err != nil {
...
return
}
// perform GET request and pass context
...
}
func main() {
router := mux.NewRouter()
// How to pass context to authCheck?
authToken, ok := getAuthToken()
if !ok {
panic("...")
}
authCheck := checkAuth(authToken)
// initialize middleware handlers
h := Handler{
...
}
// chain middleware handlers and pass context
router.Handle("/hello", util.UseMiddleware(authCheck, Handler, ...))
}
【问题讨论】:
-
你想使用 go 1.7 中引入的上下文来实现中间件,还是你想在 1.7 之前实现具有自己上下文的中间件?使用
Request.Context、Request.WithContext和context.WithValue等新引入的方法,前者会容易得多 -
我正在使用 go 1.7 并且喜欢使用 Request.Context。
标签: design-patterns go request timeout