发布于 2025-12-10 0 阅读
0

(Tiny)转到 WebAssembly Hello World Tiny Go

(Tiny)转到 WebAssembly

你好世界

Tiny Go

地鼠不仅长得可爱,而且力气也很大。

我❤️静态类型语言,Golang也是静态类型的。

Golang 在语法上与 C 类似,但具有内存安全性、垃圾收集和 CSP 风格的并发性。 -维基百科

我们可以将 Go 编译成WebAssembly。这意味着我们可以用 Golang 编写通道并在浏览器上运行它们。

Golang 中的 WebAssembly 仍处于早期阶段。🦄

Golang 编写非常简单。因此,只要现有应用程序不包含任何 WebAssembly 在运行时无法使用的文件路径或系统级功能,就可以很容易地将其直接编译为 WebAssembly 模块。

你好世界

创建一个名为 的文件夹,go-wasm其中包含子文件夹out和go;

 go-wasm/
 |__ out/
 |__ go/
Enter fullscreen mode Exit fullscreen mode

main.go在文件夹内建立一个名为的文件go并输入以下内容:

package main

func main() {
    println("Hello World!!!")
}
Enter fullscreen mode Exit fullscreen mode

使用 运行 go 文件go run go/main.go。这将打印Hello World。是不是很简单?

现在我们可以将其编译成 WebAssembly 模块并作为 WebAssembly 运行。

GOOS=js GOARCH=wasm go build -o out/main.wasm go/main.go
Enter fullscreen mode Exit fullscreen mode

main.wasm这将在文件夹内生成out。与 Rust 不同,Golang 不会生成任何绑定文件。我们可以使用 TinyGo 官方仓库中提供的绑定文件。

下载文件并将其移动到out目录内。

index.html在目录内创建一个文件out并添加以下内容:

<!doctype html>
<html>
        <head>
                <meta charset="utf-8">
                <title>Go wasm</title>
        </head>

        <body>
                <script src="wasm_exec.js"></script>
                <script>
                        const go = new Go();
                        WebAssembly.instantiateStreaming(fetch('main.wasm'),go.importObject).then( res=> {
                                go.run(res.instance)    
                        })
                </script>

        </body>
</html>

Enter fullscreen mode Exit fullscreen mode

该文件会index.html加载wasm_exec.js。请注意,此文件适用于浏览器和 NodeJS 环境。它会导出一个Go对象。

然后我们添加一个本地脚本。在脚本中我们执行以下操作:

从文件夹运行本地服务器以查看Hello World。

等等,我们正在写 Golang 代码。用 Golang 写一个简单的 Web 服务器相当容易。那就让我们来写一个吧。

webServer.go在根目录中创建一个名为的文件,其内容如下。

package main

import (
        "log"
        "net/http"
        "strings"
)

const dir = "./out"

func main() {
        fs := http.FileServer(http.Dir(dir))
        log.Print("Serving " + dir + " on http://localhost:8080")
        http.ListenAndServe(":8080", http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
                resp.Header().Add("Cache-Control", "no-cache")
                if strings.HasSuffix(req.URL.Path, ".wasm") {
                        resp.Header().Set("content-type", "application/wasm")
                }
                fs.ServeHTTP(resp, req)
        }))
}
Enter fullscreen mode Exit fullscreen mode

这将为文件夹内的文件提供服务out。现在使用 运行服务器go run webServer.go。🎉 是不是很简单?

前往http://localhost:8080并打开控制台来查看精彩内容Hello World。

目录结构应如下所示。

├── go
│   └── main.go
└── out
    ├── index.html
    ├── wasm_exec.js
    └── main.wasm
Enter fullscreen mode Exit fullscreen mode

注意生成的 WebAssembly 模块的文件大小非常重要。仅仅一个 Hello World 代码就高达 1.3MB。这可真是个大工程啊。

-rw-r--r--  1 sendilkumar  staff   482B Jul  5 23:20 index.html
-rwxr-xr-x  1 sendilkumar  staff   1.3M Jul  5 23:19 main.wasm
-rw-r--r--  1 sendilkumar  staff    13K Jul  5 23:18 wasm_exec.js
Enter fullscreen mode Exit fullscreen mode

WebAssembly 可能提供的任何性能,如果模块很大,则不需要它。

别担心,我们有 Teeny TinyGO。

Tiny Go

TinyGo 是一个旨在将 Golang 引入微控制器和现代 Web 浏览器的项目。他们拥有一个基于 LLVM 进行编译的全新编译器。使用 TinyGo,我们可以生成经过优化、可在芯片上执行的极简库。

在此处查看如何安装 TinyGo 。

安装完成后,您可以使用 TinyGo 编译任何 Golang 代码。我们可以使用以下命令将 Golang 编译为 WebAssembly 模块。

tinygo build -o out/main.wasm -target wasm ./go/main.go
Enter fullscreen mode Exit fullscreen mode

现在转到浏览器并刷新页面即可看到Hello World仍然打印的内容。

最重要的是生成的 WebAssembly 模块只有 3.8K 🎉 🎉 🎉

-rw-r--r--  1 sendilkumar  staff   482B Jul  5 23:20 index.html
-rwxr-xr-x  1 sendilkumar  staff   3.8K Jul  5 23:29 main.wasm
-rw-r--r--  1 sendilkumar  staff    13K Jul  5 23:18 wasm_exec.js
Enter fullscreen mode Exit fullscreen mode

由于底层使用了 LLVM,我们可以使用该-opt标志进一步调整它。最大尺寸优化是通过 -opt=z 标志获得的,并且TinyGo默认使用该标志。因为这些微型设备的内存有限。

敬请期待下篇文章,让我们使用 TinyGo 和 WebAssembly 重新创建经典的 Dev 离线页面。

希望以上内容能激励你开启精彩的 WebAssembly 之旅。如果你有任何问题/建议,或者觉得我遗漏了什么,欢迎随时留言。

您可以在Twitter上关注我。

如果你喜欢这篇文章,请点赞或者留言。❤️

鏂囩珷鏉ユ簮锛�https://dev.to/sendilkumarn/tiny-go-to-web assembly-5168