2

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

 2 years ago
source link: http://siongui.github.io/2016/01/25/go-http-request-header-by-xhr-getAllResponseHeaders/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

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

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:

[2]Bindings · gopherjs/gopherjs Wiki · GitHub

[5]Using XMLHttpRequest - Web APIs | MDN


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK