webassembly例子
创建服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package main
import ( "fmt" "os" "strconv"
"github.com/gin-gonic/gin" )
func main() { port := 8080 if len(os.Args) == 2 { port, _ = strconv.Atoi(os.Args[1]) } engine := gin.Default() engine.Static("/", ".") err := engine.Run(fmt.Sprintf("0.0.0.0:%d", port)) if err != nil { fmt.Println(err.Error()) } }
|
正常编译即可
1
| go build -o simpleserver
|
创建wasm文件
1 2 3 4 5 6 7 8 9
| package main
import "fmt"
func main() { res := 10 fmt.Println(res) }
|
使用以下命令编译
1
| GOARCH=wasm GOOS=js go build -o main.wasm
|
创建前端工程
1
| cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
|
运行wasm文件需要以上js文件支持,如果使用app之类的库可能还需要引入别的js文件,以下为index.html内容
1 2 3 4 5 6 7 8 9 10 11 12 13
| <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>
|
将main.wasm,wasm_exec.js,index.html和simpleserver放在同一目录,运行./simpleserver访问页面在浏览器控制台可以看到输出
文档
https://github.com/golang/go/wiki/WebAssembly