XMLHttpRequest (XHR) in Go
This post shows how to interact with servers from browsers. Send data to URL or retrieve data from URL from your browser via XMLHttpRequest method in Go/GopherJS. The full code example of this post is on my GitHub.
Table of Content
Retrieve Data From URL
In this example, we will show you how to get data from URL. We will get JSON data from a URL and print the JSON data on the browser console.
JavaScript
var URL = "https://siongui.github.io/xemaauj9k5qn34x88m4h/sacca.json";
function GetJSON() {
console.log(this.responseText);
}
var req = new XMLHttpRequest();
req.addEventListener("load", GetJSON);
req.open("GET", URL);
req.send();
This example is modified from example on MDN. We get JSON file from the URL and print the data on the console.
GopherJS
The above code in Go/GopherJS is as follows:
package main
import (
"github.com/gopherjs/gopherjs/js"
)
var URL = "https://siongui.github.io/xemaauj9k5qn34x88m4h/sacca.json"
func GetJSON(url string) {
req := js.Global.Get("XMLHttpRequest").New()
req.Call("addEventListener", "load", func() {
println(req.Get("responseText").String())
})
req.Call("open", "GET", url, true)
req.Call("send")
}
func main() {
GetJSON(URL)
}
Idomatic Go without import GopherJS
Thanks to the great jobs done by GopherJS guys, you can use methods from net/http package in Go standard library to retrieve data from a URL, just like you are writing a local Go program. GopherJS will compile the code and translate the Go code to the corresponding JavaScript XMLHttpRequest for you! You do not even have to know about XMLHttpRequest!
package main
import (
"bytes"
"net/http"
)
var URL = "https://siongui.github.io/xemaauj9k5qn34x88m4h/sacca.json"
func GetJSON(url string) {
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return
}
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
println(buf.String())
}
func main() {
GetJSON(URL)
}
Run Code on GopherJS Playground
The result of above code is the same as the Go code in previous section. Just compile the code with GopherJS, and the JavaScript code output from GopherJS will run with the same result! Amazing!
References:
[1] | GopherJS XMLHttpRequest (XHR) and MakeFunc Example |
[2] | [Golang] XMLHttpRequest (XHR) HTTP POST JSON Data by GopherJS |
[3] | [Golang] XMLHttpRequest (XHR) HTTP GET JSON Data by GopherJS |
[4] | [Golang] Access HTTP Request Header by XHR getAllResponseHeaders() |
[5] | [Golang] Caveats of GopherJS Development |