值得期待:Go对WebAssmbly的完全支持

john_f_lau · · 57 次点击 · · 开始浏览    
版权声明:本文为博主John Lau原创文章,未经博主允许不得转载 https://blog.csdn.net/GreatElite/article/details/78855667

WebAssembly获得了所有浏览器的一致支持, Chrome 和 Firefox 已经原生支持 WebAssembly,Edge 和 Safari 也在预览版中加入了 WebAssembly 支持。

Go很快也会对WebAssembly进行支持,目前还处理开发阶段。社区已经有对应的指导文档,下面就是社区的部分指导步骤。

Compiling Go code to wasm is also doable, but the support for this backend hasn’t been yet integrated into gc. An issue is tracking the progress of this feature: https://github.com/golang/go/issues/18892. As that discussion is quite long, here is the executive summary: a development branch with preliminary support for wasm has been created by @neelance (Richard Musiol) (yeah!).

Here are the instructions to compile a gc toolchain with a GOOS=js GOARCH=wasm environment:

$> cd somewhere
$> git clone https://go.googlesource.com/go
$> cd go
$> git remote add neelance https://github.com/neelance/go
$> git fetch --all
$> git checkout wasm-wip
$> cd src
$> ./make.bash
$> cd ../misc/wasm

The misc/wasm directory contains all the files (save the actual wasm module) to execute a wasm module with nodejs.

Let us compile the following main.go file:

package main

func main() {
    println("Hello World, from wasm+Go")
}

with our new wasm-capable go binary:

$> GOARCH=wasm GOOS=js go build -o test.wasm main.go
$> ll
total 4.0K
-rw-r--r-- 1 binet binet   68 Dec 14 14:30 main.go
-rwxr-xr-x 1 binet binet 947K Dec 14 14:30 test.wasm
Copy over the misc/wasm files under this directory, and then finally, run the following server.go file:

package main

import (
    "flag"
    "log"
    "net/http"
)

func main() {
    addr := flag.String("addr", ":5555", "server address:port")
    flag.Parse()
    srv := http.FileServer(http.Dir("."))
    log.Printf("listening on %q...", *addr)
    log.Fatal(http.ListenAndServe(*addr, srv))
}

Like so:

$> ll
total 968K
-rw-r--r-- 1 binet binet   68 Dec 14 14:30 main.go
-rw-r--r-- 1 binet binet  268 Dec 14 14:38 server.go
-rwxr-xr-x 1 binet binet 947K Dec 14 14:30 test.wasm
-rw-r--r-- 1 binet binet  482 Dec 14 14:32 wasm_exec.html
-rwxr-xr-x 1 binet binet 7.9K Dec 14 14:32 wasm_exec.js

$> go run ./server.go
2017/12/14 14:39:18 listening on ":5555"...

Navigating to localhost:5555/wasm_exec.html will present you with a [Run] button that, when clicked should display “Hello World, from wasm+Go” in the console.

We’ve just had our browser run a wasm module, generated with our favorite compilation toolchain!

WebAssembly 的出现则提供了一个更好的选择:接近原生的运算效率,开源、兼容性好、平台覆盖广的标准,以及可以借此机会抛弃 JavaScript 的历史遗留问题。

欢迎加入我的微信公众号

欢迎加入我的微信公众号

本文来自:CSDN博客

感谢作者:john_f_lau

查看原文:值得期待:Go对WebAssmbly的完全支持

57 次点击  
加入收藏 微博
下一篇:go build
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传