0
votes

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
1
Use http.ServeMux and register a handler under the "/" pattern, then have the handler do whatever and after that execute the gorilla mux's ServeHTTP method passing it the w and r.mkopriva
@mkopriva, very interesting solution. Can you write an answer? I will accept ItAli Mamedov

1 Answers

2
votes

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)