Detect Browser Language Preference in Go


To build a multilingual website, it is important to know language preferences of users. There are two ways for frontend programmers to detect browser language preference:

  • Via NavigatorLanguage API: This API contains properties (language and languages) to indicate the preferred language of the browser user. This post will mainly focus on how to use this API.
  • Via Accept-Language header in HTTP request: There is no way to directly access this header in your code. You can, however, run a server which returns the headers to client browser via JSONP. See [3] for more details.

Access NavigatorLanguage API

navigator.language returns the preferred language of the user, while navigator.languages returns languages known to the user.

JavaScript

console.log(navigator.language);
console.log(navigator.languages);

The return value of navigator.language is string, and the return value of navigator.languages is an array.

GopherJS

The above code in Go/GopherJS is as follows:

import (
      "github.com/gopherjs/gopherjs/js"
)

println(js.Global.Get("navigator").Get("language").String())
println(js.Global.Get("navigator").Get("languages").String())

Run Code on GopherJS Playground

Note that the return value of both are strings because of the constraint of GopherJS compiler.

GopherJS + godom

To make your code more readable, we can prettify the above code with godom:

import (
      . "github.com/siongui/godom"
)

println(Window.Navigator().Language())
println(Window.Navigator().Languages())

The full code example of this post is on my GitHub.


References:

[1][Golang] Detect Browser Language Preference by window.navigator.language
[2][Golang] GopherJS Synonyms with JavaScript
[3][Golang] Access HTTP Request Header (Accept-Language) by JSONP