full-stack go with gopherjs
TRANSCRIPT
Let's talk about JavaScript
JavaScript is becoming a platform
X compiles to JavaScript, X = almost anything
Trend: asm.js, WebAssembly... not designed to be written by human
Why
Learn once, Write everywhere
Better tooling compares to JavaScript: gofmt, gooracle, gorename...
Easy concurrency: channels and goroutines instead of callback.
GopherJS
compiles Go into JavaScript
sourcemap
compatibility is really good. support channels and goroutines
can compile itself!
GopherJS Playground (http://gopherjs.github.io/playground/)
Example: https://github.com/shurcooL/Go-Package-Store (https://github.com/shurcooL/Go-Package-Store)
Export Function
func main() { js.Global.Set("pet", map[string]interface{}{ "New": New, })}
type Pet struct { name string}
func New(name string) *js.Object { return js.MakeWrapper(&Pet{name})}
func (p *Pet) Name() string { return p.name}
func (p *Pet) SetName(name string) { p.name = name}
Callback
func main() { js.Global.Call("requestAnimationFrame", raf)}
func raf(t float64) { js.Global.Call("requestAnimationFrame", raf)
dt := (t - last) / 1000 go animate(dt) last = t}
Bindings
DOM: honnef.co/go/js/dom (honnef.co/go/js/dom)
jQuery: github.com/gopherjs/jquery (github.com/gopherjs/jquery)
JS console: honnef.co/go/js/console (honnef.co/go/js/console)
WebGL: github.com/gopherjs/webgl (github.com/gopherjs/webgl)
WebSocket: github.com/gopherjs/websocket (github.com/gopherjs/websocket)
XHR: honnef.co/go/js/xhr (honnef.co/go/js/xhr)
Import Carefully
No dead code elimiation yet
hello world with fmt
// 753kbimport "fmt"
func main () { fmt.Println("hello world")}
hello world with JS API
// 64kbimport "github.com/gopherjs/gopherjs/js"
func main () { js.Global.Get("console").Call("log", "hello world")}
Blocking
Callbacks should never be blocking
// this will produce an errorjs.Global.Get("myButton").Call("addEventListener", "click", func() { someBlockingFunction()})
Wrap it into a goroutine to fix it
// this works!js.Global.Get("myButton").Call("addEventListener", "click", func() { go func() { someBlockingFunction() }()})
Good Architecture
OP = Custom Byte Code
Design as whatever you like
{ "op": "move", "target": "player", "params": { "x": 100, "y": 100}}
<xml><enterprise><op>move</op><target>player</target></enterprise></xml>
Text-based protocol: Cross-platform, Easy to debug, Easy to parse
Recap
Write your core logic in Go: Cross-platform, even in browser
Provide text-based protocol for "Write once, run anywhere"