How to Run GoLang (1.15+) Code in a Browser Using WebAssembly
Why Do We Need WebAssembly?
Today web and mobile applications are the primary vehicles for providing software solutions to users around the world. Applications that we had only in desktop apps today are available for browsers like graphics, photo and video editors; music and video players; and so on.
In this article, we will learn how to create a project with GoLang in a browser using WebAssembly.
Step 1: Create Our Go File
First, we will create a sample Go file to compile to Wasm (WebAssembly binary code). In this case, we will print “Hello, WebAssembly” in the console. After these initial steps, we will add more content to this file to make it a more useful example.
To run the binary code in a browser, we have to generate the
The loader file is available in your standard Go installation. Just copy it into the project folder with the following command:
$ cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
Step 3: Compile the Main.go File
To compile our
main.go file for the web, we will set two environment variables:
GOARCH. We will set
GOOS, which stands for Go Operating System, to
js. We will set
GOARCH, which stands for Go Architecture, to
wasm. Then we can compile our file using the Go build…