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 make cross-domain requests (CORS) by JSONP
(JSON with Padding) technique, which allows data to be retrieved from servers of
other domains.
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).
First we write a simple HTML for our demo: (index.html)
<!doctype html><html><head><title>JSONP example of Full-Stack Golang</title></head><body><scriptsrc="demo.js"></script></body></html>
A callback function whose name is mycallback are declared by js.Global.Set
method. The mycallback function will receive JSON data from the server.
Beside, a script element are inserted to the head element to make
cross-domain request.
The server receive the name of the callback function and data from the client.
Then encode the data in JSON format, and send the JSON data to the callback
function.
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:
$gorunserver.go
Open your browser with URL localhost:8000. Open the
console of the browser, and you will see the data printed out by the callback
function.
Tested on: Ubuntu Linux 15.10, Go 1.5.3,
Chromium Version 47.0.2526.106 Ubuntu 15.10 (64-bit).