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 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输