[Golang] Access HTTP Request Header (Accept-Language) by JSONP


Introduction

To detect browser language preference (user locale), one of the solution is to access Accept-Language field in HTTP Request Header. We cannot, however, access the Accept-Language field in our browser code directly. One of the answers in Stack Overflow question [4] provides an cloud service on Google App Engine to return you the HTTP request headers via JSONP. In this post, we will show you how to write Go code which runs on browsers to retrieve HTTP request headers via JSONP by GopherJS and its DOM binding.

Note that you can get similar information to detect user locale by alternative solution - browser NavigatorLanguage API. This API provides you the same information of preferred language of the user. See [5] for more details.

Install GopherJS

Run the following command to install GopherJS and GopherJS bindings for the JavaScript DOM APIs:

$ go get -u github.com/gopherjs/gopherjs
$ go get -u honnef.co/go/js/dom

Source Code

HTML file for demo: (index.html)

<!doctype html>
<html>
<head>
  <title>Golang - access HTTP Request Header (Accept-Language) by JSONP
         to detect browser language preference</title>
</head>
<body>
<script src="demo.js"></script>
</body>
</html>

The Golang code for retrieving HTTP request headers via JSONP:

jsonp.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package main

import "github.com/gopherjs/gopherjs/js"
import "honnef.co/go/js/dom"

func main() {
	js.Global.Set("mycallback", func(headers map[string]string) {
		println(headers)
		println(headers["Accept-Language"])
		println(headers["User-Agent"])
	})

	targetUrl := "http://ajaxhttpheaders.appspot.com/?callback=mycallback"

	d := dom.GetWindow().Document()
	ext := d.CreateElement("script")
	ext.SetAttribute("src", targetUrl)
	head := d.GetElementsByTagName("head")[0].(*dom.HTMLHeadElement)
	head.AppendChild(ext)
}

Compile Go code to JavaScript by:

$ gopherjs build jsonp.go -o demo.js

Put demo.js together with the index.html in the same directory. Open the index.html with your browser, and then open the browser console to see the result.


Tested on: Ubuntu Linux 15.10, Go 1.5.3, Chromium Version 47.0.2526.106 Ubuntu 15.10 (64-bit).


References:

[1]GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, godoc)
[2]Bindings · gopherjs/gopherjs Wiki · GitHub
[3]dom - GopherJS bindings for the JavaScript DOM APIs (GitHub)
[4]localization - JavaScript for detecting browser language preference - Stack Overflow
[5][Golang] Detect Browser Language Preference by window.navigator.language
[6]Navigator - Web APIs | MDN