Running Golang WebAssembly in the Browser
WebAssembly, often abbreviated as “wasm”, is a binary instruction format designed as a portable target for compiling high-level languages like C, C++, and Rust. In addition, WebAssembly was intended as a low-level virtual machine that runs code at near-native speed in web browsers using standard hardware capabilities.
- Go installed on your system (version
- A modern web browser that supports WebAssembly
Table of Contents:
- Setting Up the Go Environment for WebAssembly
- Creating the Go Code
- Compiling the Go Code to WebAssembly
- Running the Application
Setting Up the Go Environment for WebAssembly
First, make sure your Go environment is set up correctly. You should have Go installed and configured on your system. If you don’t have Go installed, download it from the official Go website.
You’re all set if you have Go version
1.11 or later.
Creating the Go Code
Create a new Go file named
main.go and add the following code:
This code defines a simple Go function,
multiply, that takes two integers and returns their product. The
Compiling the Go Code to WebAssembly
Next, compile the Go code to WebAssembly with the following command:
This command will create a
main.wasm file in the current directory.
Create a new file named
index.html and add the following content:
main.wasm file, and runs the Go WebAssembly code.
When the user clicks the “Multiply” button, it takes the input values, calls the
multiply function exported from Go, and displays the result in the
result paragraph element.
Running the Application
To run the application using a web server, you must serve the
wasm_exec.js files. You can use any web server of your choice. In this example, we’ll use the Python built-in HTTP server. First, copy the
wasm_exec.js file from your Go installation’s
misc/wasm directory to your project folder:
Now, run the web server using the following command in the terminal:
This command starts an HTTP server on port
8080. First, navigate to
http://localhost:8080 in your browser of choice. Next, you should see a button that says, “Multiply 6 and 7.” Click the button, and “The result is 42.” should appear below it.
If you’re interested in further exploring the world of web development and cloud technologies, I invite you to read our previous articles. Start with our “Friendly Introduction to WebAssembly”, which provides an easy-to-understand overview of this powerful technology. For those looking to dive deeper into specific WASM technologies, check out our guide on Python in WebAssembly with Pyodide. These articles cover the basics and provide practical code examples to enhance your understanding and help you start your journey toward mastering web development and cloud technologies.
Subscribe to Faizan Bashir
Get the latest posts delivered right to your inbox