douzhan8303 2015-02-28 04:04
浏览 23
已采纳

一个通用的http处理程序,而不是几个

Is it possible to not copy paste expression commonHanlder(handler1), commonHanlder(handler2) ... commonHanlder(handlerN) in this code:

rtr.HandleFunc("/", commonHanlder(handler1)).Methods("GET")
rtr.HandleFunc("/page2", commonHanlder(handler2)).Methods("GET")

and set it in one place like

http.ListenAndServe(":3000", commonHanlder(http.DefaultServeMux))

But this variant is not working and gives two errors on compile:

./goRelicAndMux.go:20: cannot use http.DefaultServeMux (type *http.ServeMux) as type gorelic.tHTTPHandlerFunc in argument to commonHanlder
./goRelicAndMux.go:20: cannot use commonHanlder(http.DefaultServeMux) (type gorelic.tHTTPHandlerFunc) as type http.Handler in argument to http.ListenAndServe:
    gorelic.tHTTPHandlerFunc does not implement http.Handler (missing ServeHTTP method)

The full code:

package main

import (
    "github.com/gorilla/mux"
    "github.com/yvasiyarov/gorelic"
    "log"
    "net/http"
)

func main() {
    initNewRelic()
    rtr := mux.NewRouter()
    var commonHanlder = agent.WrapHTTPHandlerFunc

    rtr.HandleFunc("/", commonHanlder(handler1)).Methods("GET")
    rtr.HandleFunc("/page2", commonHanlder(handler2)).Methods("GET")

    http.Handle("/", rtr)
    log.Println("Listening...")
    http.ListenAndServe(":3000", http.DefaultServeMux)
}

func handler1(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("mainPage"))
}

func handler2(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("page 2"))
}

var agent *gorelic.Agent

func initNewRelic() {
    agent = gorelic.NewAgent()
    agent.Verbose = true
    agent.NewrelicName = "test"
    agent.NewrelicLicense = "new relic key"
    agent.Run()
}
  • 写回答

1条回答 默认 最新

  • douye2110 2015-02-28 04:27
    关注

    It seems like you want to call commonHandler on the root of your application and have it work for all. Since you are using mux, just wrap the mux router once.

    func main() {
        initNewRelic()
        rtr := mux.NewRouter()
        var commonHandler = agent.WrapHTTPHandler
    
        rtr.HandleFunc("/", handler1).Methods("GET")
        rtr.HandleFunc("/page2", handler2).Methods("GET")
    
        http.Handle("/", commonHandler(rtr))
        log.Println("Listening...")
        http.ListenAndServe(":3000", nil)
    }
    

    I also removed the http.DefaultServeMux reference in ListenAndServe since passing nil will automatically use the default.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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?
  • ¥15 乘性高斯噪声在深度学习网络中的应用