Getting Started with WebAssembly in Go: A Step-by-Step Guide

WebAssembly (Wasm) has emerged as a potent alternative to JavaScript for web applications. It offers performance improvements, compact binary format, and allows us to use languages other than JavaScript on the web. One of the languages that has extensive support for WebAssembly is Go.

In this blog post, we'll provide a beginner-friendly guide on setting up your first Wasm module using Go. So, let's dive in!

Prerequisites:

  1. Go installed (You can download it from the official Go website).

  2. A basic understanding of Go syntax and structure.

1. Setting Up the Environment:

First, let's create a new Go project:

mkdir go-wasm-example
cd go-wasm-example
go mod init wasm-example

2. Writing the Go Code:

Create a file named main.go:

package main

import (
	"fmt"
	"syscall/js"
)

func greet(this js.Value, args []js.Value) interface{} {
	message := fmt.Sprintf("Hello, %s!", args[0].String())
	alert := js.Global().Get("alert")
	alert.Invoke(message)
	return nil
}

func registerCallbacks() {
	js.Global().Set("greetFromGo", js.FuncOf(greet))
}

func main() {
	c := make(chan struct{}, 0)
	registerCallbacks()
	<-c
}

Here we're defining a function greet which can be called from JavaScript. The function takes a string as an argument and shows an alert with a greeting message.

3. Compiling to WebAssembly:

To compile the Go code to WebAssembly, execute:

GOOS=js GOARCH=wasm go build -o main.wasm main.go

This will create a main.wasm file, which is the compiled WebAssembly binary.

4. Creating the Web Page:

To interact with our Wasm module, let's create an HTML file. Create a file named index.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Go and WebAssembly Example</title>
</head>

<body>
    <input type="text" id="nameInput" placeholder="Enter your name">
    <button onclick="callGoFunction()">Greet me!</button>

    <script src="wasm_exec.js"></script>
    <script>
        const go = new Go();
        WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then(result => {
            go.run(result.instance);
        });

        function callGoFunction() {
            const name = document.getElementById("nameInput").value;
            greetFromGo(name);
        }
    </script>
</body>

</html>

Note: We reference a file wasm_exec.js in the script above. This file comes with Go and provides necessary functionalities to interface with WebAssembly. You can find it in your Go installation directory under $GOROOT/misc/wasm/. Copy wasm_exec.js to your project folder.

5. Running the Web Server:

To run our example, we'll use a simple HTTP server. If you have Python installed, you can use its built-in server. Navigate to your project directory and execute:

python3 -m http.server 8080

Then, visit http://localhost:8080 in your web browser.

Conclusion:

Congratulations! You've successfully created your first WebAssembly module using Go. By now, you should have a basic understanding of the process, and you're ready to explore more advanced topics and incorporate Wasm into larger projects. Happy coding!

Previous
Previous

Advanced Go WebAssembly: Exploring the Go Standard Library's Wasm Offerings

Next
Next

Performance Implications: Generics in Go