网站建设 策划方案,wordpress分站,南宁vi设计公司,网站 .net 多少钱WebAssembly (WASM) 是一种新的编码方式#xff0c;可以在现代的网络浏览器中运行#xff0d; 它是一种低级的类汇编语言#xff0c;具有紧凑的二进制格式#xff0c;可以接近原生的性能. 可以将C/C/Rust/GO代码编译成.wasm文件, 然后运行在web上面.本文仅介绍Golang与WASM…WebAssembly (WASM) 是一种新的编码方式可以在现代的网络浏览器中运行 它是一种低级的类汇编语言具有紧凑的二进制格式可以接近原生的性能. 可以将C/C/Rust/GO代码编译成.wasm文件, 然后运行在web上面.本文仅介绍Golang与WASM使用的相关基础知识.环境需要golang版本高于go1.11, 本文golang版本:$ go versiongo version go1.11.1 darwin/amd64js中调用golang函数案例本案例基于goland IDE编写, 为了获取syscall/js库的自动提示, 需要对IDE进行如下设置:设置好之后, 进行编辑go文件: main.gopackage mainimport (fmtsyscall/js
)func foo( args []js.Value) {fmt.Println(hellow wasm)fmt.Println(args)
}func main() {// 将golang中foo函数注入到window.foo中js.Global().Set(foo, js.NewCallback(foo))// 将100注入到 window.value中js.Global().Set(value, 100)select {}
}
将此main.go文件, 编译成wasm文件:GOARCHwasm GOOSjs go build -o test.wasm main.go接下来需要开启一个简单的web服务器并将上一步的wasm文件复制到案例目录中:server.go:package mainimport net/httpfunc main() {http.ListenAndServe(:8080, http.FileServer(http.Dir(./test1))) // 此为案例文件夹目录
}
将golang源码中的wasm_exec.js复制到本案例中:cp $GOROOT/misc/wasm/wasm_exec.js .index.html:html
headmeta charsetutf-8script srcwasm_exec.js/scriptscriptconst go new Go();WebAssembly.instantiateStreaming(fetch(test.wasm), go.importObject).then((result) {go.run(result.instance);});/script
/head
body/body
/html整体案例文件:$ tree test1
test1
├── index.html
├── server.go
├── test.wasm
└── wasm_exec.js运行 go run server.go即可启动服务浏览器中访问 http://127.0.0.1:8080/index.html, 右键-检查-console即可对golang中的函数 以及 属性进行访问.GO获取DOM元素, 操作标签属性同样的方式, main.go中:package mainimport (syscall/js
)func setDivRedColor(args []js.Value) {// 获取DOM元素, 进行设置属性, call方法为调用js方法js.Global().Get(document).Call(getElementById, div).Set(style, width: 300px; height: 300px; background-color: red)// 注意, 此处设置style的时候, 是会覆盖掉html中的style设置
}func main() {js.Global().Set(setDivRedColor, js.NewCallback(setDivRedColor))select {}
}
进行编译, 得到wasm文件, 复制到案例项目中项目中server.go不变, index.html改为:html
headmeta charsetutf-8script srcwasm_exec.js/scriptscriptconst go new Go();WebAssembly.instantiateStreaming(fetch(test.wasm), go.importObject).then((result) {go.run(result.instance);});/script
/head
bodydiv stylewidth: 300px; height: 300px; background-color: yellow iddiv/div
/body
/html启动服务, 浏览器访问http://127.0.0.1:8080/index.html当console中调用对应的golang函数:总结以上就是Go中使用WASM的基本方式, golang对于WASM支持也在不断的加强. 此案例编译生成的wasm文件为1.4M, 后续也许会优化缩小.