wasm
目录结构
wasm/main.go
编译为 wasm 字节码,可以被 js 调用
package main
import (
"fmt"
"syscall/js"
)
var htmlString = `<h4>Hello,I'm an HTML snippet from Go!</h4>`
func GetHtml() js.Func {
return js.FuncOf(func(this js.Value, args []js.Value) interface{} {
return htmlString
})
}
func main() {
// 利用chan来阻塞
ch := make(chan struct{}, 0)
fmt.Printf("Hello Wasm from Go\n")
// 程序没有阻塞,直接执行完,则set的方法也会跟着被清除
js.Global().Set("getHtml", GetHtml())
<-ch
}
server/main.go
服务器,用于展示运行 web 程序
package main
import (
"log"
"net/http"
)
func main() {
log.Fatal(http.ListenAndServe(":9000", http.FileServer(http.Dir("../../assets"))))
}
assets/
index.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Hello Wasm</h1>
<button id="get-html">Get Html</button>
<script src="wasm_exec.js"></script>
<script src="script.js"></script>
</body>
</html>
script.js
wasm_exec.js 是从 go 安装目录的 misc/wasm/目录里复制出来的
const goWasm = new Go();
WebAssembly.instantiateStreaming(fetch("main.wasm"), goWasm.importObject).then(
(result) => {
goWasm.run(result.instance);
document.getElementById("get-html").addEventListener("click", () => {
document.body.innerHTML += getHtml();
});
}
);
build.bat
编译 wasm
set GOOS=js
set GOARCH=wasm
go build -o ../../assets/main.wasm
# 重新设置回windows的环境
SET GOOS=windows
SET GOARCH=amd64