Golang简单使用wasm

发布时间 2023-11-07 17:32:49作者: 朝阳1

go代码

package main

import (
	"syscall/js"
)

func addxxxx(this js.Value, args []js.Value) interface{} {
	if len(args) != 2 {
		return "Invalid number of arguments. Expected 2."
	}

	num1 := args[0].Float()
	num2 := args[1].Float()
	result := num1 + num2
	return result
}

func main() {
	js.Global().Set("addxxxx", js.FuncOf(addxxxx))
	done := make(chan struct{}, 0)
	<-done
}

把编译后的wasm复制到静态文件目录/path/to/static,类似于js,css。。。

GOOS=js GOARCH=wasm go build -o go_main.wasm

将 Golang SDK 中的 wasm_exec.js 复制到工作目录 /path/to/static 改成你的路径

cp "$GOROOT/misc/wasm/wasm_exec.js" /path/to/static

前端html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Go WebAssembly Calculator</title>
    <script src="./wasm_exec.js"></script> //加载刚才复制的js
    <script>
        // 在页面加载完毕后执行
        window.onload = function() {
            const go = new Go(); // wasm_exec.js 中的定义
            WebAssembly.instantiateStreaming(fetch('./main2.wasm'), go.importObject)
                .then(res => {
                    go.run(res.instance); // 执行 go main 方法
                });
        };

        function calculate() {
            const num1 = parseFloat(document.getElementById("num1").value);
            const num2 = parseFloat(document.getElementById("num2").value);
            console.log(window)
            const result = window.addxxxx(num1, num2);

            document.getElementById("result").innerHTML = result;
            return new Promise(()=>{

            })
        }
    </script>
</head>
<body>
<h1>Simple Calculator</h1>

 <input type="number" id="num1" value="1" placeholder="Number 1"> <br>
    <input type="number" id="num2" value="2" placeholder="Number 2"><br>

<button onclick="calculate()">Calculate</button>

<h2>Result: <span id="result"></span></h2>

</body>
</html>