【探索WebAssembly】使用Go语言编写的WebAssembly小栗子

596 阅读2分钟

WebAssembly 概念

WebAssembly,简称Wasm,是一种开放标准的二进制指令格式。它的设计目标是在Web浏览器中提供高性能的代码执行能力。借助WebAssembly,开发者可以使用各种编程语言编写代码,然后将其编译成Wasm模块,这些模块可以在浏览器中迅速运行。它不仅仅是一项技术,更是一场Web开发的进化。

工作原理

WebAssembly的核心是其精简的二进制格式和中间表示(IR)。开发者使用支持Wasm的编程语言编写代码,然后通过编译器将其转换为Wasm模块。这些模块可以在浏览器中加载和运行,就如同释放了魔法的力量。这种高效的工作机制让WebAssembly成为现代Web应用不可或缺的一环。

小Demo

WebAssembly并非孤立存在,它与JavaScript紧密合作,共同构建Web应用的未来。举个例子,假设你正在开发一个在线的计算器工具。你可以在JavaScript中调用WebAssembly模块,让它处理复杂的数学运算,然后将结果传递给JavaScript继续处理。这就如同你在和一位合作伙伴协同工作,各自发挥优势,共同创造价值。

本文将使用go编写一个计算器小Demo,来初步体验一下 Wasm 的使用。

我们将创建一个简单的计算器应用,将两个数字相加并在浏览器中显示结果。

1. 编写 Go 代码:

定义一个在 Go 中编写的函数 add,用于将两个数字相加。然后,我们将这个函数通过 js.Global().Set("add", js.FuncOf(add)) 注册到全局作用域,使得 JavaScript 可以调用它。

首先,创建一个名为 main.go 的文件,其中包含我们的计算逻辑。

package main

import (
        "fmt"
        "syscall/js"
)

func add(this js.Value, p []js.Value) interface{} {
        a := p[0].Int()
        b := p[1].Int()
        result := a + b
        return js.ValueOf(result)
}

func main() {
        c := make(chan struct{}, 0)

        js.Global().Set("add", js.FuncOf(add))

        <-c
}

2. 编译为 WebAssembly:

使用 Go 工具编译 Go 代码为 WebAssembly 格式。

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

3. 创建 HTML 文件:

创建一个名为 index.html 的 HTML 文件,用于加载 WebAssembly 模块并与之交互。

创建一个简单的界面,允许用户输入两个数字,然后通过 JavaScript 调用 Go 的 WebAssembly 函数来计算并显示结果。

<!DOCTYPE html>
<html>
<head>
    <title>Go WebAssembly Calculator</title>
</head>
<body>
    <h1>Go WebAssembly Calculator</h1>
    <p>Enter two numbers to add:</p>
    <input id="num1" type="number">
    <input id="num2" type="number">
    <button onclick="calculate()">Calculate</button>
    <p>Result: <span id="result"></span></p>
    <script src="main.wasm"></script>
    <script>
        async function calculate() {
            const num1 = parseInt(document.getElementById('num1').value);
            const num2 = parseInt(document.getElementById('num2').value);

            const result = await add(num1, num2);
            document.getElementById('result').textContent = result;
        }
    </script>
</body>
</html>

4. 运行应用:

在终端中启动一个 HTTP 服务器,然后在浏览器中访问应用。

goexec 'http.ListenAndServe(":8080", http.FileServer(http.Dir(".")))'