0
0

Goによるlocale(言語と地域の設定)の取得

Last updated at Posted at 2024-01-06

はじめに

多言語対応などのために、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に渡すケースもあります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0