[Golang] Access HTTP Request Header by XHR getAllResponseHeaders()


Introduction

Access HTTP Request Header in Golang code running on your browser. This can be done by getAllResponseHeaders() method in XMLHttpRequest (XHR) request, as discussed in [4]. According to my test, many important fields such as Accept-Language, however, are missing, which makes this technique useless. I suggest you use another technique [6] to access HTTP request headers.

Install GopherJS and XHR binding

Run the following command to install GopherJS and GopherJS bindings for the XMLHttpRequest API:

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

Source Code

HTML file for demo: (index.html)

<!doctype html>
<html>
<head>
  <title>Golang - access HTTP Request Header
         by XHR getAllResponseHeaders()</title>
</head>
<body>
<script src="demo.js"></script>
</body>
</html>

The Golang code for retrieving HTTP request headers via getAllResponseHeaders():

getAllResponseHeaders.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package main

import "honnef.co/go/js/xhr"

func main() {
	req := xhr.NewRequest("GET", "/")
	err := req.Send(nil)
	if err != nil { println(err) }
	headers := req.ResponseHeaders()
	println(headers)
}

Compile Go code to JavaScript by:

$ gopherjs build getAllResponseHeaders.go -o demo.js

Put demo.js together with the index.html in the same directory. You need a simple HTTP server to run this demo. Use GopherJS serve command to serve the above files, and open your browser console to see the output. My output is:

Date: Sun, 24 Jan 2016 20:11:53 GMT
Last-Modified: Fri, 22 Jan 2016 12:59:37 GMT
Accept-Ranges: bytes
Content-Length: 145
Content-Type: text/html; charset=utf-8

Appendix

If you want to use GopherJS native API only without XHR binding, you can use the following code:

getAllResponseHeaders-raw.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

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

func main() {
	req := js.Global.Get("XMLHttpRequest").New()
	req.Call("addEventListener", "load", func() {
		headers := req.Call("getAllResponseHeaders").String()
		println(headers)
	})
	req.Call("open", "GET", "/", true)
	req.Call("send")
}

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]Package xhr provides GopherJS bindings for the XMLHttpRequest API (GitHub)
[4]Accessing the web page's HTTP Headers in JavaScript - Stack Overflow
[5]Using XMLHttpRequest - Web APIs | MDN
[6][Golang] Access HTTP Request Header (Accept-Language) by JSONP