0
votes

I'm using Gorilla mux as my router and dispatcher in my golang apps and I have a -I think- simple question:

In my main, I create a router: r := mux.NewRouter(). A few lines further, I register a handler: r.HandleFunc("/", doSomething).

So far so good, but now my problem is that I have a package which adds handlers to the http package of Golang and not to my mux router. Like this:

func AddInternalHandlers() {
    http.HandleFunc("/internal/selfdiagnose.html", handleSelfdiagnose)
    http.HandleFunc("/internal/selfdiagnose.xml", handleSelfdiagnose)
    http.HandleFunc("/internal/selfdiagnose.json", handleSelfdiagnose)
}

As you can see, it adds handles to the http.HandleFunc and not to the mux-handleFunc. Any idea how I can fix this without touching the package itself?

Working example

package main

import (
    "fmt"
    "log"

    "net/http"

    selfdiagnose "github.com/emicklei/go-selfdiagnose"
    "github.com/gorilla/mux"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
    log.Println("home")
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", homeHandler)

    selfdiagnose.AddInternalHandlers()

  // when handler (nil) gets replaced with mux (r), then the
  // handlers in package selfdiagnose are not "active"
    err := http.ListenAndServe(fmt.Sprintf("%s:%d", "localhost", 8080), nil)
    if err != nil {
        log.Println(err)
    }

}
1
Are you asking how you could extract the handlers from the DefaultServeMux and insert them into your Router? It would probably be more maintainable to fix your package to not register the handlers like that.JimB
The problem is that it is not my package :).Rogier Lommers
So, is that what you're asking? Or maybe you want to add your router to the DefaultServeMux?JimB
I think my skills to explain my problem are not that well :). Please see the working example I have just added to my initial question.Rogier Lommers

1 Answers

1
votes

Well, in your particular case, the solution is easy.

The author of the selfdiagnose package choose to make handlers themselves public, so you can just use them directly:

r.HandleFunc("/", homeHandler)
// use the handlers directly, but you need to name a route yourself
r.HandleFunc("/debug", selfdiagnose.HandleSelfdiagnose)

Working example: https://gist.github.com/miku/9836026cacc170ad5bf7530a75fec777