0

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()
}
Maxim Yefremov
  • 13,671
  • 27
  • 117
  • 166

1 Answers1

1

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.

Logiraptor
  • 1,496
  • 10
  • 14
  • `http.Handle("/", commonHanlder(rtr))` gives error `cannot use rtr (type *mux.Router) as type gorelic.tHTTPHandlerFunc in argument to commonHanlder command ` – Maxim Yefremov Feb 28 '15 at 05:08
  • 1
    Ah, yes. I overlooked that. Since rtr is not a function, but an http.Handler, you need to use agent.WrapHTTPHandler not agent.WrapHTTPHandlerFunc – Logiraptor Mar 01 '15 at 05:44