实现 URL 级的多语言路由
想实现全局有个默认语言比如中间件判断 accept-language 。设置 ctx 。
然后访问 /hi 就显示默认语言(mux.Vars()[locale]等于"",而不是 hi) 访问 /en/hi 就强制显示成 en 语言。
gorilla 可以实现自定义 matcher 吗?或者有其他路由组件能支持吗?
1
bv 207 天前
以标准库为例:
``` package main import ( "fmt" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/hi", Language) mux.HandleFunc("/{lang}/hi", Language) http.ListenAndServe(":9999", mux) } func Language(w http.ResponseWriter, r *http.Request) { lang := r.PathValue("lang") if lang == "" { lang = r.Header.Get("Accept-Language") } fmt.Println(lang) w.Write([]byte(lang)) } ``` |
2
hingle 207 天前
有个方案,可以中间件获取到 locale 后,重定向到 /{locale}/hi
|
3
dzdh OP |
4
xiaoyiyu 207 天前
```go
var global = http.NewServeMux() var mux1 = http.NewServeMux() mux1.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) { }) global.Handle("/", mux1) global.Handle("/{locale}/", mux1) http.ListenAndServe("", global) ``` 这样试下 |
7
xiaoyiyu 206 天前
```go
var langs = map[string]bool{ "cn": true, "en": true, "jp": true, "ru": true, } func main() { var global = http.NewServeMux() var mux = http.NewServeMux() mux.HandleFunc("/api/asd", func(w http.ResponseWriter, r *http.Request) { fmt.Println("hello asadsdd") fmt.Fprintf(w, "hello format") }) global.Handle("/{locale}/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Println(r.PathValue("locale")) if lng := r.PathValue("locale"); langs[lng] { http.StripPrefix("/"+lng, mux).ServeHTTP(w, r) } else { mux.ServeHTTP(w, r) } })) http.ListenAndServe(":12345", global) } ``` ➜ curl http://localhost:12345/en/api/asd hello format% ➜ curl http://localhost:12345/cn/api/asd hello format% ➜ curl http://localhost:12345/api/asd hello format% ➜ curl http://localhost:12345/ad/api/asd 404 page not found 看效果是满足了的 @dzdh @dzdh |