当前位置:网站首页>Go write webassembly
Go write webassembly
2022-07-21 16:35:00 【AdleyTales】
Environmental Science
- golang
- javascript
- tinygo
Code up
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 = "[email protected]!"
// Sign the string
func sign(this js.Value, args []js.Value) interface{
} {
fmt.Println("============== begin")
fmt.Println(args[0].String()) // Enter the reference
b := []byte(args[0].String())
s := []byte(salt)
h := md5.New()
h.Write(s) // Write the salt value first
h.Write(b)
result := hex.EncodeToString(h.Sum(nil))
fmt.Println(result)
fmt.Println("============== end")
return result
}
func main() {
fmt.Println("hello wasm ...")
// Register to global
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)
}
compile go Code ->wasm
tinygo build -o main-tiny.wasm
copy to wasm Bridge to current directory
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, importObject) => {
const source = await (await resp).arrayBuffer() return await WebAssembly.instantiate(source, importObject) } } function loadWasm (path) {
const go = new Go() // Solve the browser console error 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>
【 Reference link 】
边栏推荐
- In depth analysis: how chain 2+1 mode plays with investment attraction and drainage
- 2022护眼灯展,中医眼科调理展,山东眼睛保健展,中国眼博会
- [dip/ implementation of simple digital image processing system] high score course design paper sharing
- Win64 driver kernel programming -30 Enumerating and deleting thread callbacks
- 安装C3D v1.0
- Is it safe for GF futures to open an account online? Are there any account opening guidelines?
- Several stumbling blocks of it entrepreneurs
- ORA-1142 signalled during: ALTER DATABASE END BACKUP...
- Ipaylinks, a cross-border payment integration service, won the 3A Asia Award of the asset!
- What preliminary work does the enterprise need to do to establish its own applet and app?
猜你喜欢
Dama Chapter 5 (data modeling and Design)
This domestic API artifact tool is too strong Let me give up postman
[kaggle] how to effectively avoid oom (out of memory) and long alchemy process
Difference between service and systemctl / method of modifying path / a command to view IP address, gateway and DNS server
Daily question-leetcode1260-2d grid migration array mapping
安装C3D v1.0
Translation of UAV intelligent coverage navigation based on DRL in complex geometric environments
Dama Chapter 6 (data storage and operation)
Visual studio easy to use plug-in sharing
C | file operation
随机推荐
I2C client Drive
JZ76 删除链表中重复的结点
Xqlla2.3.2 parsing query
2022 the 5th China (Jinan) International Youth eye health industry exhibition was held in September
7.1-WY22 Fibonacci数列
Several stumbling blocks of it entrepreneurs
Change dimension style text fill color
How can traditional retail enterprises promote consumption cycle and share purchase mode to enable the development of physical enterprises?
In the future, a new way of tourism, VR traveling without leaving home, embracing poetry and distance
Message: no NPM package can be built. Please confirm that the NPM to be built is in the 'miniprogramroot' directory, or configure project config. Packnpmmaof JSON
Cad2014 x64 debugging ARX
Source code, complement and fixed-point number operation
Ipaylinks, a cross-border payment integration service, won the 3A Asia Award of the asset!
Let's go - Recruitment book for reading activities in 2022 (issue 1)
Tian Wei, architect of Alibaba cloud native application platform: planning, governance and evolution of application architecture
[mqtt from introduction to improvement series | 08] mqtt3.1.1 topic details
Dam Chapter 13 (data quality management)
Dama Chapter 5 (data modeling and Design)
Use priority queue_ Queue implements unordered to base_ Value filtering of map on value value value
I2C adapter driver