WebAssembly

From XennisWiki
Jump to: navigation, search

WebAssembly (often shortened to Wasm) is an open standard that defines a portable binary code format for executable programs, and a corresponding textual assembly language, as well as interfaces for facilitating interactions between such programs and their host environment. The main goal of WebAssembly is to enable high performance applications on web pages, but the format is designed to be executed and integrated in other environments as well.

Wasm does not replace JavaScript; in order to use Wasm in browsers, users may use Emscripten SDK to compile C++ (or any other LLVM-supported language such as D or Rust) source code into a binary file which runs in the same sandbox as regular JavaScript code [...]. (Wikipedia)

Go example

Create a Go program in the main.go

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello, Wolrd!")
	for i := 1; i <= 5; i++ {
		fmt.Printf("%d place\n", i)
	}
}

Compile it for Wasm by excuting GOOS=js GOARCH=wasm go build -o main.wasm

Copy the JavaScript support file

cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .

Create a simple index.html that includes the support file and the program

<html>
	<head>
		<meta charset="utf-8"/>
		<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>
	</head>
	<body></body>
</html>

Serve the files from a web server, for example use goexec (o get -u github.com/shurcooL/goexec):

goexec "http.ListenAndServe(\`:8080\`, http.FileServer(http.Dir(\`.\`)))"

See also

External links