[Golang] Caveats of GopherJS Development
Fix runtime error via goroutine in Golang code compiled to JavaScript by GopherJS. I got runtime error when writing code to make XHR requests and also code to generate HTML via html/template
The following code is an XHR request to retrieve JSON data from server: [7]
func XhrGetWordInfo(word string) (w WordInfo, err error) {
resp, err := http.Get(HttpWordJsonPath(word))
if err != nil {
return
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&w)
return
}
XhrGetWordInfo is called by:
XhrGetWordInfo("sacca")
The following error showed up in browser console: [4]
Uncaught Error: runtime error: cannot block in JavaScript callback, fix by wrapping code in goroutine
Uncaught TypeError: r is not a function
After some trial and error, the correct way to make XHR requests is: [5]
go XhrGetWordInfo("sacca")
The code must be wrapped in goroutine to prevent blocking the execution.
Similar situation [6] happened again and the same solution was applied to fix the runtime error when generating HTML via html/template.
Tested on: Ubuntu Linux 15.10, Go 1.5.3, Chromium Version 48.0.2564.82 Ubuntu 15.10 (64-bit).
References:
[1] | GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, ) |
[2] | Bindings · gopherjs/gopherjs Wiki · GitHub |
[3] | dom - GopherJS bindings for the JavaScript DOM APIs (GitHub) |
[4] | net/http not working · Issue #389 · gopherjs/gopherjs · GitHub |
[5] | use net/http by goroutine · siongui/pali@2445656 · GitHub |
[6] | fix bug: use html/template by goroutine · siongui/pali@39ffdf9 · GitHub |
[7] | handle input text enter event. Bug: net/http not working · siongui/pali@f8f1475 · GitHub |