Including context objects through multiple HTTP handlers in golang

前端 未结 2 1401
不知归路
不知归路 2021-02-06 11:46

I just read this blog post about creating a function type and implementing the .ServeHTTP() method on that function to be able to handle errors. For example:

<
相关标签:
2条回答
  • 2021-02-06 12:23

    Use r.Context(), which is available since Go 1.7.

    See https://golang.org/pkg/net/http/#Request.Context

    0 讨论(0)
  • 2021-02-06 12:34

    I can think of a couple of approaches to do this.

    Passing the context

    first you can change the signature to accept context

    type appHandler func(http.ResponseWriter, *http.Request, context.Context) *appError
    
    func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
            if e := fn(w, r, nil); e != nil { // e is *appError, not os.Error.
                    http.Error(w, e.Message, e.Code)
            }
    }
    

    Now I assume the AuthHandler has to do with authentication and setup the user in the context object.

    What you could do is create another type handler which setup the context. like this

    type authHandler func(http.ResponseWriter, *http.Request, context.Context) *appError
    
    func (fn authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {           
        // setup authentication here                                                    
        uid := 1                                                                        
    
        // setup the context the way you want                                           
        parent := context.TODO()                                                        
        ctx := context.WithValue(parent, userIdKey, uid)                                
        if e := fn(w, r, ctx); e != nil { // e is *appError, not os.Error.              
            http.Error(w, e.Message, e.Code)                                            
        }                                                                               
    }
    

    This way you can use it in the following way

    func init() {                                                                         
        http.Handle("/view", appHandler(viewRecord))      // don't require authentication 
        http.Handle("/viewAuth", authHandler(viewRecord)) // require authentication       
    }                                                                                     
    

    This is the complete code

    package main
    
    import (
            "fmt"
            "net/http"
    
            "code.google.com/p/go.net/context"
    )
    
    type appError struct {
            Error   error
            Message string
            Code    int
    }
    
    type key int
    
    const userIdKey key = 0
    
    type appHandler func(http.ResponseWriter, *http.Request, context.Context) *appError
    
    func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
            if e := fn(w, r, nil); e != nil { // e is *appError, not os.Error.
                    http.Error(w, e.Message, e.Code)
            }
    }
    
    type authHandler func(http.ResponseWriter, *http.Request, context.Context) *appError
    
    func (fn authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
            // setup authentication here
            uid := 1
    
            // setup the context the way you want
            parent := context.TODO()
            ctx := context.WithValue(parent, userIdKey, uid)
            if e := fn(w, r, ctx); e != nil { // e is *appError, not os.Error.
                    http.Error(w, e.Message, e.Code)
            }
    }
    
    func viewRecord(w http.ResponseWriter, r *http.Request, c context.Context) *appError {
    
            if c == nil {
                    fmt.Fprintf(w, "User are not logged in")
            } else {
                    uid := c.Value(userIdKey)
                    fmt.Fprintf(w, "User logged in with uid: %d", uid)
            }
    
            return nil
    }
    
    func init() {
            http.Handle("/view", appHandler(viewRecord))      // viewRecord is an appHandler function
            http.Handle("/viewAuth", authHandler(viewRecord)) // viewRecord is an authHandler function
    }
    
    func main() {
            http.ListenAndServe(":8080", nil)
    }
    

    create map context

    Instead of passing the context, you create

    var contexts map[*http.Request]context.Context
    

    and get the context in view with contexts[r].

    But because of map is not thread safe, access to the map must be protected with mutex.

    And guess what, this is what gorilla context is doing for you, and I think it's better approach

    https://github.com/gorilla/context/blob/master/context.go#l20-28

    this is the full code

    package main
    
    import (
            "fmt"
            "net/http"
    
            "github.com/gorilla/context"
    )
    
    type appError struct {
            Error   error
            Message string
            Code    int
    }
    
    type key int
    
    const userIdKey key = 0
    
    type appHandler func(http.ResponseWriter, *http.Request) *appError
    
    func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
            if e := fn(w, r); e != nil { // e is *appError, not os.Error.
                    http.Error(w, e.Message, e.Code)
            }
    }
    
    type authHandler func(http.ResponseWriter, *http.Request) *appError
    
    func (fn authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
            // setup authentication here
            uid := 1
    
            context.Set(r, userIdKey, uid)
            if e := fn(w, r); e != nil { // e is *appError, not os.Error.
                    http.Error(w, e.Message, e.Code)
            }
    }
    
    func viewRecord(w http.ResponseWriter, r *http.Request) *appError {
    
            if uid, ok := context.GetOk(r, userIdKey); !ok {
                    fmt.Fprintf(w, "User are not logged in")
            } else {
                    fmt.Fprintf(w, "User logged in with uid: %d", uid)
            }
    
            return nil
    }
    
    func init() {
            http.Handle("/view", appHandler(viewRecord))      // don't require authentication
            http.Handle("/viewAuth", authHandler(viewRecord)) // require authentication
    }
    
    func main() {
            http.ListenAndServe(":8080", nil)
    }
    

    you can also opt for wrapper function instead of type function for auth

    func AuthHandler(h appHandler) appHandler {                                   
        return func(w http.ResponseWriter, r *http.Request) *appError {
            // setup authentication here                                          
            uid := 1                                                              
    
            context.Set(r, userIdKey, uid)                                        
            return h(w, r)                                                        
        }                                                                        
    }  
    
    func init() {                                                                                    
        http.Handle("/view", appHandler(viewRecord))                  // don't require authentication
        http.Handle("/viewAuth", appHandler(AuthHandler(viewRecord))) // require authentication      
    }                                                                                               
    
    0 讨论(0)
提交回复
热议问题