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)
}
tinygo build -o main-tiny.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 Demotitle>
<script src="./wasm_exec_tiny.js">script>
head>
<body>
<script>
// polyfill
if (!WebAssembly.instantiateStreaming) {
WebAssembly.instantiateStreaming = async (resp, importObject) => {
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, reject) => {
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>