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

one common http handler instead of several

是否可以在这段代码中不复制粘贴表达式 commonHanlder(handler1)commonHanlder(handler2) ... commonHanlder(handlerN):

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

并像

一样将其设置在一个地方
http.ListenAndServe(":3000", commonHanlder(http.DefaultServeMux))

但是这个变体不起作用并且在编译时给出了两个错误:

./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)

完整代码:

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

您似乎想在应用程序的根目录上调用 commonHandler 并使其适用于所有应用程序。由于您使用的是 mux,因此只需将 mux 路由器包装一次即可。

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

我还删除了 ListenAndServe 中的 http.DefaultServeMux 引用,因为传递 nil 将自动使用默认值。