【Go】【WebAssembly】【wasm】基于go打包的网页wasm

5 篇文章 0 订阅
3 篇文章 1 订阅

基于go语言实现的wasm示例DEMO

基本环境

新建文件
index.js

const fastify = require('fastify')({ logger: true })
const path = require('path')

// Serve the static assets
fastify.register(require('fastify-static'), {
   root: path.join(__dirname, ''),
   prefix: '/'
})

const start = async () => {
   try {
       await fastify.listen(8080, "0.0.0.0")
       fastify.log.info(`server listening on ${fastify.server.address().port}`)

   } catch (error) {
       fastify.log.error(error)
   }
}
start()

package.json

{
  "scripts": {
    "dev": "node index.js"
  },
  "dependencies": {
    "fastify": "^3.6.0",
    "fastify-static": "^3.2.1"
  }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
hello
</body>
</html>

运行 npm run dev
打开http://127.0.0.1:8080
在这里插入图片描述

wasm部分

新建
go.mod

module hello-world

go 1.18

main.go

package main

import (
	"syscall/js"
)

func main() {
	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)
}

运行
go env
win下

GOOS=windows
GOARCH=amd64

需要配置环境变量为
win 下设置 cmd运行
set GOOS=js
set GOARCH=wasm

生成必要文件(cmd会报错 powershell可以执行)
cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
会多出一个wasm_exec.js的文件

go打包成wasm
运行go build -o main.wasm
运行结束后会生成一个名为main.wasm的文件

然后修改之前的index.html文件

<html>
<head>
    <meta charset="utf-8"/>
    <script src="wasm_exec.js"></script>
</head>
<body>
<h1>WASM</h1>
<script>
	// 判断是否支持instantiateStreaming加载
    if (!WebAssembly.instantiateStreaming) {
        WebAssembly.instantiateStreaming = async (resp, importObject) => {
            const source = await (await resp).arrayBuffer()
            return await WebAssembly.instantiate(source, importObject)
        }
    }
    // 异步加载wasm文件
    function loadWasm(path) {
        const go = new Go()
        return new Promise((resolve, reject) => {
            WebAssembly.instantiateStreaming(fetch(path), go.importObject)
                .then(result => {
                    go.run(result.instance)
                    resolve(result.instance)
                })
                .catch(error => {
                    reject(error)
                })
        })
    }
    //加载wasm文件
    loadWasm("main.wasm").then(wasm => {
        console.log("wasm已加载 👋")
    }).catch(error => {
        console.log("加载出错了", error)
    })
</script>
</body>
</html>

然后刷新浏览器就能看到这么一个界面
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值