Search code examples
goroutesgorillamux

Gorilla mux - modify request before passing it to routers


Is there a way to catch a *http.Request object before It will be parsed and forwarded to Gorilla mux router handler?

For example, we have some routing map with their handlers:

r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)

I plan to use a dynamic language prefix (2 symbols). Example:

without language code (for default language option):

https://example.com/products/1
https://example.com/articels/2

with language code:

https://example.com/ru/products/1
https://example.com/ru/articels/2

Is there a way to catch full URL in the middleware, extract language (if exists) and then after some modifications pass It to Gorilla mux routers? It will help to build beautiful URLs:

https://example.com/products/1 <- default language
https://example.com/ru/products/1 <- russian language (same resource but in different language)

That looks more attractive than this variant:

https://example.com/en/products/1 <- mandatory default language
https://example.com/ru/products/1 <- russian language

Solution

  • Something like this will probably work:

    r := mux.NewRouter()
    r.HandleFunc("/products/{key}", ProductHandler)
    r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
    
    m := http.NewServeMux()
    m.HandeFunc("/", func(w http.ResponseWriter, req *http.Request) {
        // do something with req
        r.ServeHTTP(w, req)
    })
    http.ListenAndServe(":8080", m)