0

是否可以不复制粘贴表达式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()
}
4

1 回答 1

1

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

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 将自动使用默认值。

于 2015-02-28T04:27:20.313 回答