go - 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
解决方案
这样的事情可能会起作用:
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)
推荐阅读
- php - SQLSTATE [23000]:完整性约束违规:1052。加入表时 Laravel 雄辩的问题
- sql - 计算结果表中的其他列时如何显示列?
- java - 如何使图像在碰撞时消失,然后重新出现在屏幕上的随机位置
- python - 如何让`python3 -m venv`在环境中安装新版本的pip?
- git - libgit2-newbie 问题:提交中的文件树中有什么?
- batch-file - 截断 SystemInfo / Boot Time 输出并设置为变量?
- php - PHP示例下GCP setIamPolicy API参考中的问题
- javascript - 如何在javascript中使用计时器来绘制它?
- python - 如何动态过滤出具有完全匹配的 Spark 数据帧中的行?
- r - 我想创建一个新列,其中 3 个组的第一行和最后一行为 2,否则为 NA