16

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

 3 years ago
source link: https://siongui.github.io/2016/01/20/go-xhr-http-get-json-by-gopherjs/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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
{"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
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:

[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


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK