duanban4769 2016-12-06 22:09
浏览 66
已采纳

使用Golang Gorilla软件包设置回调

Is there an easy way to set a callback function that is called on every HTTP request made to a gorilla/mux HTTP webserver? They don't seem to have a notion of setting a callback function in their docs.

I wanted to check one of the headers for some information on every call to my server.

  • 写回答

2条回答 默认 最新

  • douhui4831 2016-12-06 22:44
    关注

    gorilla/mux itself is just a router and dispatcher, which, although technically could do what you're asking, is not really what it's designed for.

    The "idiomatic" approach is to wrap your handler with middleware that decorates your handler with any additional functions, like one to check headers for some information on every call.

    Expanding on the gorilla/mux full example, you could do something like:

    package main
    
    import (
            "log"
            "net/http"
    
            "github.com/gorilla/mux"
    )
    
    func HeaderCheckWrapper(requiredHeader string, original func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
            return func(w http.ResponseWriter, r *http.Request) {
                    if foo, ok := r.Header[requiredHeader]; ok {
                            // do whatever with the header value, and then call the original:
                            log.Printf("Found header %q, with value %q", requiredHeader, foo)
                            original(w, r)
                            return
                    }
                    // otherwise reject the request
                    w.WriteHeader(http.StatusPreconditionFailed)
                    w.Write([]byte("missing expected header " + requiredHeader))
            }
    }
    
    func YourHandler(w http.ResponseWriter, r *http.Request) {
            w.Write([]byte("Gorilla!
    "))
    }
    
    func main() {
            r := mux.NewRouter()
            // Routes consist of a path and a handler function.
            r.HandleFunc("/", HeaderCheckWrapper("X-Foo-Header", YourHandler))
    
            // Bind to a port and pass our router in
            log.Fatal(http.ListenAndServe(":8000", r))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?