首页 > 解决方案 > Gorilla mux - 在将请求传递给路由器之前修改请求

问题描述

有没有办法在*http.Request对象被解析并转发给Gorilla mux 路由器处理程序之前捕获它?

例如,我们有一些路由映射及其处理程序:

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

我计划使用动态语言前缀(2 个符号)。例子:

没有语言代码(默认语言选项):

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

带语言代码:

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

有没有办法在中间件中捕获完整的 URL,提取语言(如果存在),然后在进行一些修改后将它传递给 Gorilla mux 路由器?它将有助于构建漂亮的 URL:

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

这看起来比这个变种更有吸引力:

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

标签: goroutinggorillamux

解决方案


这样的事情可能会起作用:

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)

推荐阅读