How to Run GoLang (1.15+) Code in a Browser Using WebAssembly

Cesar William Alvarenga
4 min readNov 8, 2020
Photo made with Canva.

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.

To use a sophisticated tool in a web browser, sometimes you need to use a specific language, not JavaScript. We have to use a language that provides an easy way to build that type of application. For example, if you want to execute many things in parallel, Go enables a developer to make use of concurrency via goroutines and channels.

In this article, we will learn how to create a project with GoLang in a browser using WebAssembly.

Getting Started

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.

Step 2: Generate the Wasm JavaScript Loader

To run the binary code in a browser, we have to generate the wasm_exec.js file. It’s a JavaScript file provided by Go to load your .wasm file into a Web page.

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: GOOS and GOARCH. We will setGOOS, 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…

Recommended from Medium


See more recommendations