0
点赞
收藏
分享

微信扫一扫

go写webasmbly


环境

  • golang
  • javascript
  • tinygo

上代码

golang

package main

import (
"crypto/md5"
"encoding/hex"
"fmt"
"strings"
"syscall/js"
)

//go:export add
func add(x, y int) int {
return x + y
}

const salt = "ftmsabcd@1234!"

// 对字符串做签名
func sign(this js.Value, args []js.Value) interface{} {
fmt.Println("============== begin")
fmt.Println(args[0].String()) // 入参
b := []byte(args[0].String())
s := []byte(salt)
h := md5.New()
h.Write(s) // 先写盐值
h.Write(b)
result := hex.EncodeToString(h.Sum(nil))
fmt.Println(result)
fmt.Println("============== end")
return result
}

func main() {
fmt.Println("hello wasm ...")

// 注册到全局
js.Global().Set("sign", js.FuncOf(sign))

message := "👋 Hello World 🌍"
document := js.Global().Get("document")
h2 := document.Call("createElement", "h2")
h2.Set("innerHTML", message)
document.Get("body").Call("appendChild", h2)

<-make(chan bool)
}

编译go代码->wasm

tinygo build -o main-tiny.wasm

拷贝到wasm桥到当前目录

cp "$(tinygo env TINYGOROOT)/targets/wasm_exec.js" ./wasm_exec_tiny.js

html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wasm Demo</title>
<script src="./wasm_exec_tiny.js"></script>
</head>

<body>

<script>// polyfill
if (!WebAssembly.instantiateStreaming) {
WebAssembly.instantiateStreaming = async (resp,) => {
const source = await (await resp).arrayBuffer()
return await WebAssembly.instantiate(source, importObject)
}
}

function loadWasm (path) {
const go = new Go()

// 解决浏览器控制台报错
go.importObject.env["syscall/js.finalizeRef"] = () => { }

return new Promise((resolve,) => {
WebAssembly.instantiateStreaming(fetch(path), go.importObject)
.then(result => {
go.run(result.instance)
resolve(result.instance)
})
.catch(error => {
reject(error)
})
})
}

loadWasm("main-tiny.wasm").then(wasm => {
const o = {
name: 'adley',
age: 18,
data: [12, 32, 'dasd']
}

console.log(sign(JSON.stringify(o)))
}).catch(error => {
console.log("ouch", error)
})</script>
</body>

</html>

【参考链接】

  • ​​https://tinygo.org/getting-started/install/​​
  • ​​https://jishuin.proginn.com/p/763bfbd6c1a0​​

举报

相关推荐

0 条评论