This repository demonstrates the basics of using WebAssembly (Wasm) with the Go programming language.
- Go 1.11 or later
-
Ensure you have Go installed. You can download it from https://golang.org/dl/
-
Create a new directory for your project and navigate into it:
mkdir go-wasm-example cd go-wasm-example -
Initialize a new Go module:
go mod init go-wasm-example
-
Create the main Go file for your Wasm module:
package main import ( "syscall/js" ) func main() { c := make(chan struct{}, 0) js.Global().Set("add", js.FuncOf(add)) <-c } func add(this js.Value, args []js.Value) interface{}{ sum := 0 for _, value := range args { sum += value.Int() } return js.ValueOf(sum) }
-
Compile the Go code to WebAssembly:
GOOS=js GOARCH=wasm go build -o main.wasm
cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" ./ -
Create an HTML file to load the Wasm module:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <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 calculate(...args) { console.log(add.apply(null, args)); } </script> </head> <body> <button onclick="calculate(4, 5, 6, 99)">Calculate</button> </body> </html>
-
Start a simple web server to serve the files. You can use http-server:
npm i -g http-server
http-server -p 3000 -o
-
Open your web browser and navigate to
http://localhost:3000to see the example in action.
By following these steps, you've created a basic example of using WebAssembly with Go. You can continue to expand and experiment with more complex functionality as needed.