go-wasm/examples/function-wasm/main.go

62 lines
1.3 KiB
Go
Raw Permalink Normal View History

2019-08-06 16:03:11 +03:00
// +build js,wasm
package main
import (
2019-08-22 20:05:05 +03:00
"crypto/rand"
"errors"
2019-08-20 23:47:40 +03:00
"log"
2019-08-06 16:03:11 +03:00
"syscall/js"
)
2019-08-20 22:20:20 +03:00
func addition(this js.Value, args []js.Value) interface{} {
2019-08-20 23:47:40 +03:00
log.Println("In WASM", args)
2019-08-20 22:20:20 +03:00
a, b := args[0].Int(), args[1].Int()
return a + b
2019-08-06 16:03:11 +03:00
}
2019-08-22 05:24:07 +03:00
func multiplier(this js.Value, args []js.Value) interface{} {
return 10
}
2019-08-22 20:05:05 +03:00
func getBytes(this js.Value, args []js.Value) interface{} {
r := make([]byte, 32)
_, err := rand.Read(r)
if err != nil {
panic(err)
}
2020-01-05 19:56:36 +03:00
v := js.Global().Get("Uint8Array").New(len(r))
js.CopyBytesToJS(v, r)
return v
2019-08-22 20:05:05 +03:00
}
func getError(this js.Value, args []js.Value) interface{} {
err := errors.New("test errors")
return err.Error()
}
2019-08-23 20:19:32 +03:00
func receiveSendBytes(this js.Value, args []js.Value) interface{} {
b := args[0]
2020-01-05 19:56:36 +03:00
buf := make([]byte, b.Length(), b.Length())
js.CopyBytesToGo(buf, b)
v := js.Global().Get("Uint8Array").New(len(buf))
js.CopyBytesToJS(v, buf)
return v
2019-08-23 20:19:32 +03:00
}
2019-08-06 16:03:11 +03:00
func main() {
2019-08-20 04:13:53 +03:00
ch := make(chan bool)
2019-08-07 13:47:59 +03:00
// register functions
2019-08-22 05:24:07 +03:00
js.Global().Set("addition", js.FuncOf(addition))
js.Global().Set("multiplier", js.FuncOf(multiplier))
2019-08-22 20:05:05 +03:00
js.Global().Set("getBytes", js.FuncOf(getBytes))
js.Global().Set("getError", js.FuncOf(getError))
2019-08-23 20:19:32 +03:00
js.Global().Set("bytes", js.FuncOf(receiveSendBytes))
2019-08-20 22:20:20 +03:00
2019-08-22 05:24:07 +03:00
res := js.Global().Get("addProxy").Invoke(1, 2)
2019-08-20 23:47:40 +03:00
log.Printf("1 + 2 = %d\n", res.Int())
2019-08-20 04:13:53 +03:00
<-ch
2019-08-06 16:03:11 +03:00
}