[Golang] XMLHttpRequest (XHR) HTTP POST 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 make HTTP POST requests to send JSON data to remote server. This is an example of full-stack Go, which uses Golang to develop web applications in both front-end (runs on browsers) and backend (runs on servers).

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 Post by GopherJS</title>
</head>
<body>
<script src="demo.js"></script>
</body>
</html>

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

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

import "net/http"
import "strings"

func main() {
	jsonStr := `{"title":"test","data":"none"}`
	resp, err := http.Post("/post", "application/json", strings.NewReader(jsonStr))
	if err != nil {
		// handle error
		println(err)
	}
	defer resp.Body.Close()
}

The following is backend Go code for receiving JSON data from front-end by HTTP POST method:

server.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
30
31
32
33
34
package main

import (
	"encoding/json"
	"net/http"
)

type TestData struct {
	Title string
	Data  string
}

func postHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		return
	}
	if r.URL.Path != "/post" {
		return
	}

	decoder := json.NewDecoder(r.Body)
	d := TestData{}

	// should handle error here
	decoder.Decode(&d)
	print(d.Title)
	print(d.Data)
}

func main() {
	http.Handle("/", http.FileServer(http.Dir("./src")))
	http.HandleFunc("/post", postHandler)
	http.ListenAndServe(":8000", nil)
}

Compile the Go code to JavaScript by:

$ gopherjs build xhrpost.go -o demo.js

Put demo.js together with the index.html and in the same directory. Modify the path in server.go to the path where you place demo.js and index.html. Run the server by:

$ go run server.go

Open your browser with URL localhost:8000. You will see the console running server.go prints out data received from front-end.


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]encoding/json - The Go Programming Language
[7][Webapp] Dart HTTP POST JSON Data to Go Server
[8]golang static file server
[9]How do you serve a static html file using a go web server? - Stack Overflow
[10]golang http post
[11]rest - Go lang - How send json string in POST request - Stack Overflow
[12]strings - The Go Programming Language
[13]bytes - The Go Programming Language