Running Go in the Browser
I wanted to add a "gamified" element to my homepage without distracting users from my articles. A completely interactive game felt too distracting. A zero-player game made the most sense for this, and what else but Conway's Game of Life?
I had one issue though. I didn't feel like writing this purely in JavaScript. I wanted the main logic to exist in Go. I'll admit there's not much reason to do this, it would likely not run into performance issues in a JavaScript implementation. Sometimes though, you gotta do things just to see if you can.
The Setup
How do we run Go in the browser, when the browser only knows JavaScript? Well, the browser has been learning a new language called Web Assembly (WASM). We can compile our Go code to Web assembly in order to run it in the browser.
The Tool
I decided to use TinyGo to generate the WASM binary. TinyGo allows us to compile simple Go programs down to WASM without including a lot of overhead, keeping the binary size at a tiny 10kb. We want that file to be small because the Go server has to send it over the internet to your browser.
The Process
Here are the high level steps that I took to run Go in the browser:
- During the build phase of my app, it generates the static HTML files. It also compiles the WASM file.
- During the run phase of the server, the server will serve the WASM file at a specific URL.
- The browser will have JavaScript that fetches the WASM file from that URL and knows how to execute it.
- The WASM file simulates the game and writes game state to a specific pointer (memory address).
- The JavaScript reads directly from the memory address that represents the game state and then writes it to the web page canvas.
- The JavaScript tells the WASM file to simulate the next iteration of the game. Repeat steps 4-6.
Conclusion
I wanted to keep it short, but that's the gist of how I ran Go in the browser. It was incredibly fun, and maybe in the future I'll do more with WASM.