How can I pass data from middleware to handlers?

后端 未结 3 534
小鲜肉
小鲜肉 2021-01-04 01:27

I am designing my handlers to return a http.Handler. Here\'s the design of my handlers:

 func Handler() http.Handler {
  return http.HandlerFunc(func(w http.         


        
3条回答
  •  半阙折子戏
    2021-01-04 01:46

    Since you're already using Gorilla take a look at the context package.

    (This is nice if you don't want to change your method signatures.)

    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")
        })
    }
    

提交回复
热议问题