Last active
February 5, 2023 12:57
-
-
Save codefromthecrypt/edb33284354d592dc6056b9b7263872f to your computer and use it in GitHub Desktop.
wazero devops win
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
_ "embed" | |
"fmt" | |
"log" | |
"github.com/tetratelabs/wazero" | |
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1" | |
) | |
//go:embed add.wasm | |
var addWasm []byte | |
// main is a simple WebAssembly program to showcase the packaging simplicity of wazero. | |
// This works because https://github.com/tetratelabs/wazero doesn't require CGO. | |
// | |
// Given a go.mod like so: | |
// | |
// module test | |
// go 1.20 | |
// | |
// And a Dockerfile like so: | |
// | |
// FROM scratch | |
// COPY wazero /wazero | |
// ENTRYPOINT ["/wazero"] | |
// | |
// Build like this: | |
// | |
// version=v1.0.0-pre.8 | |
// go get github.com/tetratelabs/wazero@${version} | |
// curl -sSL https://github.com/tetratelabs/wazero/raw/${version}/examples/basic/testdata/add.wasm > add.wasm | |
// GOOS=linux go build -o wazero main.go | |
// | |
// Then, package like this: | |
// | |
// docker build --platform linux/$(go env GOARCH) -t wazero . | |
// | |
// Finally, you end up with about 4MB even with an embedded JIT compiler! | |
// | |
// docker run --rm wazero | |
// docker history wazero:latest | |
func main() { | |
// Choose the context to use for function calls. | |
ctx := context.Background() | |
// Create a new WebAssembly Runtime. | |
r := wazero.NewRuntime(ctx) | |
defer r.Close(ctx) // This closes everything this Runtime created. | |
// Instantiate WASI, which implements host functions needed for TinyGo to | |
// implement `panic`. | |
wasi_snapshot_preview1.MustInstantiate(ctx, r); | |
// Instantiate the guest Wasm into the same runtime. It exports the `add` | |
// function, implemented in WebAssembly. | |
mod, err := r.InstantiateModuleFromBinary(ctx, addWasm) | |
if err != nil { | |
log.Panicln(err) | |
} | |
// Get a handle to the function defined in wasm. | |
add := mod.ExportedFunction("add") | |
// Discover 1 + 2 = 3 | |
results, err := add.Call(ctx, 1, 2) | |
if err != nil { | |
log.Panicln(err) | |
} | |
fmt.Println(results[0]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment