Router in Go - run a function before every HTTP request
I am using Go with http with Go like this:
mux := http.NewServeMux()
mux.HandleFunc("/API/user", test)
mux.HandleFunc("/authAPI/admin", auth)
and I would like to run the function before every HTTP request and better yet, run the function on every request that has / authAPI /. how can i achieve this in Go?
+3
source to share
2 answers
In addition to what @Thomas suggested, you can wrap the entire mux in your own mux, which is called before any handler is called, and can just call your own handlers. This is how alternative http routers are implemented in go. Example:
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Handled %s", r.RequestURI)
}
func main(){
// this will do the actual routing, but it not mandatory,
// we can write a custom router if we want
mux := http.NewServeMux()
mux.HandleFunc("/foo", handler)
mux.HandleFunc("/bar", handler)
// we pass a custom http handler that does preprocessing and calls mux to call the actual handler
http.ListenAndServe(":8081", http.HandlerFunc(func (w http.ResponseWriter, r *http.Request){
fmt.Fprintln(w, "Preprocessing yo")
mux.ServeHTTP(w,r)
}))
}
+2
source to share
You can just write a wrapper function:
func wrapHandlerFunc(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
// ...
// do something
// ...
handler(w, req)
}
}
And use it like this:
mux.HandleFunc("/authAPI/admin", wrapHandlerFunc(auth))
Doing it automatically for everything under the given URL tree (subprocessor, in mux
parlance) is not supported as far as I know.
+1
source to share