Gorilla mux-在将请求传递给路由器之前修改请求

问题描述 投票:0回答:1

在解析*http.Request对象并将其转发到Gorilla mux router处理程序之前,是否有办法捕获它?

例如,我们有一些带有其处理程序的路由图:

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多路复用器路由器?这将有助于建立漂亮的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
go routing gorilla mux
1个回答
0
投票

类似的事情可能会起作用:

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)
© www.soinside.com 2019 - 2024. All rights reserved.