Slide 9
Slide 9 text
Accept-Languageヘッダのパース
■ language.ParseAcceptLanguage関数を使う
● (*language.Matcher).Matchメソッドがフォールバックしてくれる
var matcher = language.NewMatcher([]language.Tag{ language.Japanese, language.English})
type langKey struct{}
func WithLanguge(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t, _, _ := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
tag, _, _ := matcher.Match(t...)
ctx := context.WithValue(r.Context(), langKey{}, tag)
h.ServeHTTP(w, r.WithContext(ctx))
})
}
func LangFromContext(ctx context.Context) language.Tag {
if tag, ok := ctx.Value(langKey{}).(language.Tag); ok { return tag }
return language.Und
}
func main() {
http.Handle("/", WithLanguge(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, display.Self.Name(LangFromContext(r.Context())))
})))
http.ListenAndServe(":8080", nil)
}