[Go WebAssembly] XMLHttpRequest (XHR)
This post shows how to interact with servers from browsers. Retrieve data from URL from your browser via Go WebAssembly. See demo first:
Go Wasm XMLHttpRequest (XHR) Demo
Using XMLHttpRequest is the most common way to issue HTTP requests for data exchange between browsers and servers. In Go Wasm, we do not need to deal with XMLHttpRequest at all for data exchange. We can write idomatic Go code and use net/http package in Go standard library to issue HTTP requests. You do not even have to know about XMLHttpRequest!
The following is the source code of the demo:
Go:
package main
import (
"bytes"
"fmt"
"net/http"
)
func GetJson(url string) (json string, err error) {
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
err = fmt.Errorf("response status code: %d", resp.StatusCode)
return
}
var buf bytes.Buffer
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return
}
json = buf.String()
return
}
func main() {
json, err := GetJson("https://siongui.github.io/xemaauj9k5qn34x88m4h/sacca.json")
if err != nil {
panic(err)
}
fmt.Println(json)
}
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Go wasm - XMLHttpRequest (XHR)</title>
</head>
<body>
Please open developer console to see the retrieved JSON data from server.
<!-- https://github.com/golang/go/blob/master/misc/wasm/wasm_exec.js -->
<script src="wasm_exec.js"></script>
<script>
const go = new Go();
let mod, inst;
WebAssembly.instantiateStreaming(
fetch("xhr.wasm", {cache: 'no-cache'}), go.importObject).then((result) => {
mod = result.module;
inst = result.instance;
run();
});
async function run() {
await go.run(inst);
};
</script>
</body>
</html>
Nothing special in above HTML code. Most of the HTML code is to load compiled wasm module. If you have no idea what it means, see [1].
The full source code is also available in my GitHub repo.
Tested on:
- Ubuntu Linux 18.04
- Go 1.11.1
- Chromium Version 69.0.3497.81 on Ubuntu 18.04 (64-bit)
References:
[1] | [Go WebAssembly] First Wasm Program - Hello World |
[2] | XMLHttpRequest (XHR) in Go (GopherJS) |