How do I compile Go code to WebAssembly?

Compiling Go code to WebAssembly allows you to run Go applications in web browsers, making it a powerful tool for web development. Follow these steps to compile your Go code into WebAssembly format.

Go, WebAssembly, Go WebAssembly, Compile Go to WebAssembly, Web development with Go, Go code example

This guide shows how to compile Go code to WebAssembly, enabling you to execute Go applications within a web browser environment. Ideal for developers looking to integrate Go with frontend technologies.


        // Install the Go compiler and setup your Go environment
        
        // Create a simple Go program (main.go)
        package main

        import (
            "syscall/js"
            "fmt"
        )

        func main() {
            ch := make(chan struct{}, 0)

            // Register a function to be called from JavaScript
            js.Global().Set("sayHello", js.FuncOf(sayHello))

            <-ch // Prevent the program from exiting
        }

        func sayHello(this js.Value, p []js.Value) interface{} {
            fmt.Println("Hello from Go WebAssembly!")
            return nil
        }

        // To compile to WebAssembly run:
        // GOOS=js GOARCH=wasm go build -o main.wasm main.go
    

After compiling your Go code into a WebAssembly file (main.wasm), you can load it in an HTML page using the following script:


        
        
                                
        
    

Go WebAssembly Go WebAssembly Compile Go to WebAssembly Web development with Go Go code example