duannong1801 2014-11-05 04:01
浏览 50
已采纳

通过golang中的多个HTTP处理程序包含上下文对象

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:

type appError struct {
    Error   error
    Message string
    Code    int
}

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

func init() {
    http.Handle("/view", appHandler(viewRecord)) //viewRecord is an appHandler function
}

I like this approach but I can't conceptually figure out how to include a context object through handler layers. For example:

func init() {
    http.Handle("/view", AuthHandler(appHandler(viewRecord))) 
}

AuthHandler would likely create a &SessionToken{User: user} object and set that in a context.Context object for each request. I can't work out how to get that to the viewRecord handler though. Ideas?

  • 写回答

2条回答 默认 最新

  • dongwu3596 2014-11-05 09:54
    关注

    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      
    }                                                                                               
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况