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 make HTTP POST
requests to send JSON data to remote server.
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>XHR HTTP Post by GopherJS</title></head><body><scriptsrc="demo.js"></script></body></html>
It is surprising easy to send HTTP POSTXHR request: Use Golang built-in
net/http package! You just use Post method as usual, and GopherJS will take
care of all the rests for you!
packagemainimport("encoding/json""net/http")typeTestDatastruct{TitlestringDatastring}funcpostHandler(whttp.ResponseWriter,r*http.Request){ifr.Method!="POST"{return}ifr.URL.Path!="/post"{return}decoder:=json.NewDecoder(r.Body)d:=TestData{}// should handle error heredecoder.Decode(&d)print(d.Title)print(d.Data)}funcmain(){http.Handle("/",http.FileServer(http.Dir("./src")))http.HandleFunc("/post",postHandler)http.ListenAndServe(":8000",nil)}
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. You will
see the console running server.go prints out data received from front-end.