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

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 的历史遗留问题。

欢迎加入我的微信公众号

欢迎加入我的微信公众号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值