はじめに
多言語対応などのために、Goによるlocale(言語と地域の設定)の取得方法の一例を記載します。
要点
Request HeaderのAccept-Languageを取得する。
HeaderになかったらSessionの中身を取得する。(既に設定しているかもしれない)
一切設定されていないならデフォルト値を設定する。
実際にコードを見てみよう
func GetLocale(w http.ResponseWriter, req *http.Request) (locale string){
locale := req.Header.Get("Accept-Language")
session := sessions.GetSession(req)
default := “en-us”
if locale == "" {
l := session.Get("locale")
if l == nil {
locale = default
} else {
locale = l.(string)
}
}
session.Set("locale", locale)
return locale;
}
見たままですが、一番の肝はヘッダーの中から言語、地域設定に値する"Accept-Language"を取得するところですね。ここはブラウザなどで設定した言語設定が取得されます。
locale := req.Header.Get("Accept-Language")
ここからはoptionですが、下のようにコンテキストを設定したりしてもいいですね。
ctx := context.WithValue(req.Context(), "locale", locale)
不要な部分をstring.Splitなどで削除する、ミドルウェアとして使用して他のHandlerに渡すケースもあります。