是否可以不在此代码中复制粘贴表达式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()
}
答案 0 :(得分:1)
您似乎想在应用程序的根目录上调用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会自动使用默认值。