Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use gorilla middleware handlers for all requests?

Tags:

go

router

mux

I want to use the handlers specified here for logging everything.

This is what I have:

r := mux.NewRouter()
s := r.PathPrefix("/api/v1").Subrouter()

s.HandleFunc("/abc", handler.GetAbc).Methods("GET")
s.HandleFunc("/xyz", handler.GetXyz).Methods("GET")

I want to use the logging middleware but I don't want to repeat it in every single line, as they show in github:

r.Handle("/admin", handlers.LoggingHandler(os.Stdout, http.HandlerFunc(ShowAdminDashboard)))
r.HandleFunc("/", ShowIndex)

Is there a way to just pass the general logging middleware to r, and everything that passes the r router will pass by the middleware first?

like image 982
Lucas Avatar asked Dec 10 '22 00:12

Lucas


2 Answers

Use a middleware:

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Do stuff here
        log.Println(r.RequestURI)
        // Call the next handler, which can be another middleware in the chain, or the final handler.
        next.ServeHTTP(w, r)
    })
}


r.Use(loggingMiddleware)

Here's the doc: https://github.com/gorilla/mux#middleware

like image 73
Burak Serdar Avatar answered Jan 05 '23 11:01

Burak Serdar


I wrapped the LoggingHandler with a middleware function

func loggingMiddleware(next http.Handler) http.Handler {
    return handlers.LoggingHandler(os.Stdout, next)
}

r.Use(loggingMiddleware)
like image 31
Lucas Avatar answered Jan 05 '23 10:01

Lucas