go 基础 WebAssembly
th.jpeg
我们为什么需要 webAssembly 以及如何实现使用 WebAssembly
那么什么是 WebAssembly 呢
- 用于 web 的全新的底层的字节码
- 字节码是可以通过其余语言编译得来
- 提供 web 的性能
现在不仅是理论上,会给大家分享少量 webassembly 的实现,并且会展望少量未来
首先我们来看一看 WebAssembly 到底给我们带来了什么,以及选择 WebAssembly 的理由。
- 当然首先选择 WebAssembly 就是他可以提高 web 的性能,WebAssembly 所能够提供的性能是无法通过 javascript 能够实现的。javascript 的引擎已经尽可能地提高了 javascript 的性能。WebAssembly 则在底层提供更优更稳固的性能
- 还有就是 WebAssembly 的友好性,可以将其余相似 c++ 的语言编译为 WebAssembly 来使用,也可以使用开源的第三方。我们知道 c++ 可以 Android 和 ios 平台编写,同样也支持 Web 端
- 给我们编写 Web 应用除了 javascript 以外提供更多语言的选择,以后 WebAssembly kotlin 和 .Net
我们回顾一下 web 发展的历史
- 第一个web 网页在 1991 当时只是提供少量可以跳转的静态页
- 随着 10 天就设计出来的 javascript 的出现,出现 web 应用 gmail
- 随后就是 javascript 库盛行的时代
- jquery 操作 dom
- angular 这样的SPA 的框架
- three.js 让我们在 web 可以呈现 3D 效果
- 而后就是现代 web 时代V8、WegGL、Html5、serviceworks
有了这些才让 google docs trello 和 mirosoft365 这些原来的桌面应用成为了 web 端的应用。
1523691204_go-webassembly.png
今天我带大家用 go 语言来实现一个 hello world 的 demo。go 语言对于 web 开发者总是那么友好。
600_468861629.jpeg.png
需要做少量准备工作安装 gopherjs ,gopherjs 可以将 go 编译后运行在浏览器上。
go get -u github.com/gopherjs/gopherjs我这里使用 gopm 这个工具下载安装gopherjs。
gopm get -v -g github.com/gopherjs/gopherjscp $(go env GOROOT)/misc/wasm/wasm_exec.{html,js} .我们可以初始化两个文件:
- wasm_exec.js
- wasm_exec.html
在wasm_exec.html文件中,我们看到调用assembly文件代码如下,所以我们需要将 main.go 文件编译为test.wasm文件。
WebAssembly.instantiateStreaming(fetch("test.wasm"), go.importObject)<!doctype html><!--Copyright 2018 The Go Authors. All rights reserved.Use of this source code is governed by a BSD-stylelicense that can be found in the LICENSE file.--><html><head> <meta charset="utf-8"> <title>Go wasm</title></head><body> <script src="wasm_exec.js"></script> <script> if (!WebAssembly.instantiateStreaming) { // polyfill WebAssembly.instantiateStreaming = async (resp, importObject) => { const source = await (await resp).arrayBuffer(); return await WebAssembly.instantiate(source, importObject); }; } const go = new Go(); let mod, inst; WebAssembly.instantiateStreaming(fetch("test.wasm"), go.importObject).then((result) => { mod = result.module; inst = result.instance; document.getElementById("runButton").disabled = false; }); async function run() { console.clear(); await go.run(inst); inst = await WebAssembly.instantiate(mod, go.importObject); // reset instance } </script> <button onClick="run();" id="runButton" disabled>Run</button></body></html>if (!WebAssembly.instantiateStreaming) { // polyfill WebAssembly.instantiateStreaming = async (resp, importObject) => { const source = await (await resp).arrayBuffer(); return await WebAssembly.instantiate(source, importObject); }; }判断WebAssembly.instantiateStreaming能否存在,假如不存在我们通过其余方法实现WebAssembly.instantiateStreaming函数功能。WebAssembly.instantiateStreaming异步加载 *.wasm的 webAssembly 文件,成功加载test.wasm文件后取消 run 按钮的禁用,run 按钮的点击事件是运行
WebAssembly.instantiateStreaming(fetch("test.wasm"), 这里可以写简单的 hello world ,用 go run main.go 命令查看一下输出。
package mainfunc main() { println("Hello World")}而后通过命令将main.go编译为test.wasm文件
GOARCH=wasm GOOS=js go build -o test.wasm main.go接下来我们还需要写一个server.go来启动我们服务运行 wasm_exec.html。
package mainimport( "flag" "log" "net/http" // "strings")var ( listen = flag.String("listen",":8080","listen address") dir = flag.String("dir",".","directory to serve"))func main() { flag.Parse() log.Printf("listening on %q...",*listen) log.Fatal(http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir)))) // log.Fatal(http.ListenAndServe(*listen, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request){ // if strings.HasSuffix(req.URL.Path,".wasm"){ // resp.Header().Set("content-type","application/wasm") // } // http.FileServer(http.Dir(*dir)).ServeHTTP(resp, req) // })))}在地址栏中输入localhost:8080/wasm_exec.html"看到我们如下图,这里有一个 run 按钮点击即可以调用我们的 test.wasm 中输出方法
屏幕快照 2019-04-27 下午1.17.20.png
这样在 main.go 中输出的hello world在浏览器中就成功输出了。
屏幕快照 2019-04-27 下午1.17.27.png
接下来让 webAssembly 提供少量计算函数供 web 调用,创立add函数接收参数,而后在js.Global方法将 add 方法挂在 javascript 的全局对象,这样在 chrome 的 console 中输入 add 即可以调用 webAssembly 的提供 add 方法。
package mainimport( "syscall/js")func add(i []js.Value){ js.Global().Set("output",js.ValueOf(i[0].Int() + i[1].Int())) println(js.ValueOf(i[0].Int() + i[1].Int()).String())}func registerCallbacks(){ js.Global().Set("add",js.NewCallback(add))}func main() { c := make(chan struct{},0) println("Go WebAssembly Initialized") registerCallbacks() <-c}在 registerCallbacks 函数中,
js.Global()获取 javascript 全局对象而后,通过Set方法 add 函数挂接到 javascript 的全局的 add 属性。这里是通过js.NewCallback(add)实现的。c := make(chan struct{},0)创立 channel,而后在<-c 让 goroutine 阻塞
屏幕快照 2019-04-27 下午2.15.49.png
func subtract(i []js.Value){ js.Global().Set("output",js.ValueOf(i[0].Int() - i[1].Int())) println(js.ValueOf(i[0].Int() - i[1].Int()).String()) }func registerCallbacks(){ js.Global().Set("add",js.NewCallback(add)) js.Global().Set("subtract",js.NewCallback(subtract))}
屏幕快照 2019-04-27 下午3.24.49.png
if (!WebAssembly.instantiateStreaming) { // polyfill WebAssembly.instantiateStreaming = async (resp, importObject) => { const source = await (await resp).arrayBuffer(); return await WebAssembly.instantiate(source, importObject); }; } const go = new Go(); let mod, inst; WebAssembly.instantiateStreaming(fetch("test.wasm"), go.importObject).then((result) => { mod = result.module; inst = result.instance; document.getElementById("runButton").disabled = false; }); async function run() { console.clear(); await go.run(inst); inst = await WebAssembly.instantiate(mod, go.importObject); // reset instance }修改下无需点击run我们将 test.wasm 进行加载。
const go = new Go(); let mod, inst; WebAssembly.instantiateStreaming(fetch("test.wasm"), go.importObject).then(async (result) => { mod = result.module; inst = result.instance; document.getElementById("runButton").disabled = false; await go.run(inst); }); // async function run() { // console.clear(); // inst = await WebAssembly.instantiate(mod, go.importObject); // reset instance // }
屏幕快照 2019-04-27 下午3.33.51.png
屏幕快照 2019-04-27 下午3.33.56.png
通过 gopherjs实现获取 dom 元素的值,由于类型是字符,通过strconv.Atoi方法将字符串转为int 型进行计算。
func add(i []js.Value){ value1 := js.Global().Get("document").Call("getElementById",i[0].String()).Get("value").String() value2 := js.Global().Get("document").Call("getElementById",i[1].String()).Get("value").String() int1, _ := strconv.Atoi(value1) int2, _ := strconv.Atoi(value2) js.Global().Set("output",int1 + int2) println(int1 + int2)} <input type="text" id="value1" /> <input type="text" id="value2" /> <button onClick="add('value1','value2');" id="runButton">Add</button> <button onClick="subtract(3,2);" id="runButton">Subtract</button>
屏幕快照 2019-04-27 下午3.44.24.png
这样做还不够我们还需要将计算的结果输出到 input 中,所以继续对程序改造。这里并不对 gopherjs 进行过多解释,大家可能对这些代码有些陌生,不过略微熟习 web 开发,这个应该不难了解一看就懂。
func add(i []js.Value){ value1 := js.Global().Get("document").Call("getElementById",i[0].String()).Get("value").String() value2 := js.Global().Get("document").Call("getElementById",i[1].String()).Get("value").String() int1, _ := strconv.Atoi(value1) int2, _ := strconv.Atoi(value2) js.Global().Get("document").Call("getElementById",i[2].String()).Set("value",int1 + int2) // js.Global().Set("output",int1 + int2) // println(int1 + int2)}对应修改一下 onclick 方法的参数 onClick="add('value1','value2','result');"。
<input type="text" id="value1" /> <input type="text" id="value2" /> <button onClick="add('value1','value2','result');" id="runButton">Add</button> <button onClick="subtract(3,2);" id="runButton">Subtract</button> <input id="result" type="text" />
屏幕快照 2019-04-27 下午3.48.59.png
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » go 基础 WebAssembly