WebAssembly+Go とりあえず逃がしておく

c:\Users\ebata\Desktop\codelab-master>set GOOS=js
c:\Users\ebata\Desktop\codelab-master>set GOARCH=wasm
c:\Users\ebata\Desktop\codelab-master>go build -o main.wasm
package main

import (
    "fmt"
    "syscall/js"
)

type Test struct {
    Num int
}

func (t *Test) Print(this js.Value, args []js.Value) interface{} {
    fmt.Println(t)
    return nil
}

func (t *Test) Twice(this js.Value, args []js.Value) interface{} {
    t.Num *= 2
    return nil
}


func (t *Test) Add(this js.Value, args []js.Value) interface{} {
    t.Num += args[0].Int()
    return nil
}

func (t *Test) GetNum(this js.Value, args []js.Value) interface{} {
    return js.ValueOf(t.Num)
}

func registerCallbacks() {
    var test = &Test{
        Num: 1,
    }
    js.Global().Set("test", js.ValueOf(
        map[string]interface{}{
            "Print": js.FuncOf(test.Print),
            "Twice": js.FuncOf(test.Twice),
            "Add":    js.FuncOf(test.Add),
            "GetNum": js.FuncOf(GetNum),
        },
    ))
}

func main() {
    c := make(chan struct{}, 0)
    registerCallbacks()
    <-c
}
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Go wasm</title>
</head>

<body>
    <script src="wasm_exec.js"></script>
    <script>
        const go = new Go();
        WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
            go.run(result.instance);
        });
    </script>
    <script>
        function getNum(){
            console.log(test.getNum())
        }
    </script>
    <button onClick="test.Print();" id="runButton" >print</button><br>
    <button onClick="test.Twice()" id="runButton">twice</button><br>
    <button onClick="test.Add(1)" id="runButton">add</button><br>
    <button onClick="test.GetNum()" id="runButton">get test.Num</button><br>
</body>
</html>

2020/06,江端さんの技術メモ

Posted by ebata