WebAssembly - Working with Go

Hello there, future coding superstars! Today, we're going to embark on an exciting journey into the world of WebAssembly using Go. Don't worry if these terms sound like alien languages right now - by the end of this tutorial, you'll be speaking them fluently!

WebAssembly - Working with Go

What is WebAssembly?

Before we dive into the code, let's understand what WebAssembly is. Imagine you have a super-fast race car (that's WebAssembly) that can run on any track (web browsers) at incredible speeds. It's a way to run programs written in languages like Go, C++, or Rust directly in web browsers, making web applications faster and more powerful.

Why Go with WebAssembly?

Go, our language of choice today, is like a Swiss Army knife in the programming world. It's simple, efficient, and now it can run in web browsers thanks to WebAssembly. It's like giving superpowers to your web applications!

Setting Up Our Go Environment

First things first, we need to set up our Go environment. It's like preparing our kitchen before we start cooking a delicious meal.

  1. Install Go from the official website (https://golang.org/)
  2. Set up your GOPATH (Go will guide you through this during installation)
  3. Install a code editor (I recommend Visual Studio Code, but use whatever you're comfortable with)

Our First Go WebAssembly Program

Let's start with a simple "Hello, WebAssembly!" program. Don't worry if you don't understand everything yet - we'll break it down step by step.

package main

import (
    "fmt"
    "syscall/js"
)

func main() {
    fmt.Println("Hello, WebAssembly!")
    js.Global().Set("greet", js.FuncOf(greet))
    <-make(chan bool)
}

func greet(this js.Value, args []js.Value) interface{} {
    name := args[0].String()
    message := fmt.Sprintf("Hello, %s! Welcome to WebAssembly.", name)
    js.Global().Get("document").Call("getElementById", "greeting").Set("innerText", message)
    return nil
}

Let's break this down:

  1. package main: This tells Go that this is the main package of our program.
  2. import: We're importing two packages - fmt for printing and syscall/js for interacting with JavaScript.
  3. func main(): This is the entry point of our program.
  4. js.Global().Set("greet", js.FuncOf(greet)): This makes our greet function available to JavaScript.
  5. <-make(chan bool): This keeps our program running, waiting for JavaScript calls.
  6. func greet: This function takes a name and updates an HTML element with a greeting.

Compiling Our Go Program to WebAssembly

Now, let's turn our Go code into WebAssembly. Open your terminal and run:

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

This command tells Go to compile our program for JavaScript (GOOS=js) and WebAssembly (GOARCH=wasm).

Creating an HTML Page to Run Our WebAssembly

We need an HTML page to load and run our WebAssembly. Here's a simple one:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Go WebAssembly</title>
</head>
<body>
    <h1>Go WebAssembly Demo</h1>
    <input id="name" type="text" placeholder="Enter your name">
    <button onclick="greet(document.getElementById('name').value)">Greet</button>
    <p id="greeting"></p>
    <script src="wasm_exec.js"></script>
    <script>
        const go = new Go();
        WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
            go.run(result.instance);
        });
    </script>
</body>
</html>

This HTML file:

  1. Creates an input field for a name
  2. Has a button that calls our greet function
  3. Loads the WebAssembly runtime (wasm_exec.js)
  4. Loads and runs our WebAssembly file (main.wasm)

Running Our WebAssembly Application

To run this, we need a web server. Here's a simple Python command to start one:

python -m http.server

Now, open your browser and go to http://localhost:8000. You should see our page!

Understanding the Output

When you enter your name and click "Greet", you'll see a personalized greeting appear. This is our Go function running in the browser, thanks to WebAssembly!

Conclusion

Congratulations! You've just created your first Go WebAssembly application. We've only scratched the surface here, but I hope this has sparked your curiosity to explore more.

Remember, learning to code is like learning a new language or instrument. It takes practice, patience, and perseverance. But with each step, you're unlocking new possibilities and expanding your creative potential.

Keep coding, keep exploring, and most importantly, have fun!

Method Description
js.Global() Accesses the global JavaScript object
js.FuncOf() Converts a Go function to a JavaScript function
js.Value Represents a JavaScript value
Call() Calls a JavaScript method
Set() Sets a JavaScript property
Get() Gets a JavaScript property
String() Converts a JavaScript value to a Go string

This table summarizes the key methods we used to interact between Go and JavaScript. As you continue your WebAssembly journey, you'll find these methods incredibly useful!

Credits: Image by storyset