猿问

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


杨魅力
浏览 109回答 1
1回答

慕工程0101907

这样的事情可能会起作用: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) {&nbsp; &nbsp; // do something with req&nbsp; &nbsp; r.ServeHTTP(w, req)})http.ListenAndServe(":8080", m)
随时随地看视频慕课网APP

相关分类

Go
我要回答