[Golang] XMLHttpRequest (XHR) HTTP GET JSON Data by GopherJS


Introduction

It is really cool to run Go code in the browser. GopherJS is a compiler from Go to JavaScript, which makes this possible. In this post, we will show how to use XMLHttpRequest (XHR) to send HTTP GET requests to retrieve JSON data from remote server.

Install GopherJS

Run the following command to install GopherJS:

$ go get -u github.com/gopherjs/gopherjs

Source Code

First we write a simple HTML for our demo: (index.html)

<!doctype html>
<html>
<head>
  <title>XHR HTTP Get by GopherJS</title>
</head>
<body>
<script src="demo.js"></script>
</body>
</html>

The following is the JSON data to be retrieved by HTTP GET request:

sukhada.json | repository | view raw
1
{"data": [["\u25ce\u3000\u300aConcise Pali-English Dictionary\u300b by A.P. Buddhadatta Mahathera", "sukhada", ": [adj.] producing happiness."]], "word": "sukhada"}

It is surprising easy to send HTTP GET XHR request: Use Golang built-in net/http package! You just use Get method as usual, and GopherJS will take care of all the rests for you!

xhrget2.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import "net/http"
import "encoding/json"

type Exp [3]string

type Def struct {
	Data []Exp
	Word string
}

func main() {
	resp, err := http.Get("/sukhada.json")
	if err != nil {
		// handle error
		println(err)
	}
	defer resp.Body.Close()
	w := Def{}
	dec := json.NewDecoder(resp.Body)
	err2 := dec.Decode(&w)
	if err2 != nil {
		// handle error
		println(err2)
	}
	println(w.Word)
	println(w.Data[0])
}

Compile the Go code to JavaScript by:

$ gopherjs build xhrget.go -o demo.js

Put demo.js together with the index.html and sukhada.json 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.


Tested on: Ubuntu Linux 15.10, Go 1.5.3.


References:

[1]GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, godoc)
[2]Bindings · gopherjs/gopherjs Wiki · GitHub
[3]xhr - GoDoc
[4]http - The Go Programming Language
[5]delete xhr/transport, GopherJS has its own now. · dominikh/go-js-xhr@00e3346 · GitHub
[6]go json decode array
[7]How to Unmarshal a JSON Array of Arrays in Go - Fabio Berger
[8]encoding/json - The Go Programming Language