[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:


package main

import (

func GetJson(url string) (json string, err error) {
      resp, err := http.Get(url)
      if err != nil {
      defer resp.Body.Close()

      if resp.StatusCode != 200 {
              err = fmt.Errorf("response status code: %d", resp.StatusCode)

      var buf bytes.Buffer
      _, err = buf.ReadFrom(resp.Body)
      if err != nil {
      json = buf.String()

func main() {
      json, err := GetJson("https://siongui.github.io/xemaauj9k5qn34x88m4h/sacca.json")
      if err != nil {


<!doctype html>
  <meta charset="utf-8">
  <title>Go wasm - XMLHttpRequest (XHR)</title>
  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>
      const go = new Go();
      let mod, inst;
              fetch("xhr.wasm", {cache: 'no-cache'}), go.importObject).then((result) => {
              mod = result.module;
              inst = result.instance;
      async function run() {
              await go.run(inst);

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)


[1][Go WebAssembly] First Wasm Program - Hello World
[2]XMLHttpRequest (XHR) in Go (GopherJS)