LoginSignup
13

More than 3 years have passed since last update.

GolangでWebAssemblyを触る

Last updated at Posted at 2018-12-16

マグロ大学(近畿大学)アドベントカレンダー16日目の記事です.

ちょっと予定より書く時間がなかったので当初予定していた記事とは違うやつを、、

Web Assemblyとは

ブラウザで機械語を動かして高速化を図る技術みたいです.
モダンブラウザはだいたい対応してるようです.
CとかRustで書いたコードをWeb Assemblyのバイナリにコンパイルして使えます.
Goでは1.11から対応しています.

チュートリアル

ブラウザのコンソールに文字をを出力します.

main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello wasm!")
}

.wasmにコンパイルします

GOOS=js GOARCH=wasm go build -o test.wasm main.go

.wasmを読み込むためのhtmlとjsを拾ってきます

curl -sO https://raw.githubusercontent.com/golang/go/master/misc/wasm/wasm_exec.html
curl -sO https://raw.githubusercontent.com/golang/go/master/misc/wasm/wasm_exec.js

簡易的なwebサーバーを立てます

server.go
package main

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

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))))
}

サーバーを起動します.

go run server.go

localhost:8080/wasm_exec.htmlにアクセスしてRunボタンを押してコンソールにHello wasmと表示されれば成功です.
もしここでUncaught (in promise) LinkError: WebAssembly Instantiation: Import #5 module="go" function="runtime.scheduleCallback" error: function import requires a callableと表示された場合jsファイルを https://raw.githubusercontent.com/golang/go/release-branch.go1.11/misc/wasm/wasm_exec.js に置き換えれば動くかもしれないです.

DOM操作

GoからJavaScriptを触るにはsyscall/jsを使います.

import "syscall/js"

documentオブジェクトの取得

document := js.Global().Get("document")

documentのgetElementById("text")メソッドを呼び出す

element := document.Call("getElementById", "text")

innerTextの値を取得

text := element.Get("innerText").String()

innerTextに値をセット

element.Set("innerText", "Hello World")

参考

Go WebAssembly Tutorial - Building a Calculator Tutorial | TutorialEdge.net
js - The Go Programming Language
misc/wasm: this._inst.exports.getsp is not a function · Issue #28924 · golang/go
サクッと Go → WebAssembly を試す - Qiita

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13