登录
首页 >  Golang >  Go教程

go语言打包的网页wasm示例详解

来源:脚本之家

时间:2022-12-27 21:29:51 337浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《go语言打包的网页wasm示例详解》,涉及到go打包、网页、wasm,有需要的可以收藏一下

基本环境

有时需要做一些前端的数据处理,但是又不想把数据出来的方式就这么简单的暴露在js里,然后就用了wasm来包装这个处理函数,当然,这样也能提高性能。

新建文件 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



    <meta charset="UTF-8"><title>hello</title>
hello


运行 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)
	
<p>运行 <code>go env</code> win下</p>
<blockquote><p>GOOS=windows<br>GOARCH=amd64</p></blockquote>
<p>需要配置环境变量为 win 下设置 cmd运行 <code>set GOOS=js</code> <code>set GOARCH=wasm </code></p>
<p>生成必要文件(cmd会报错 powershell可以执行) <code>cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .</code> 会多出一个<code>wasm_exec.js</code>的文件</p>
<p>go打包成wasm 运行<code>go build -o main.wasm</code> 运行结束后会生成一个名为<code>main.wasm</code>的文件</p>
<p>然后修改之前的<code>index.html</code>文件</p>
<pre class="brush:xhtml;">

    <meta charset="utf-8"><script src="wasm_exec.js"></script><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>

然后刷新浏览器就能看到这么一个界面

今天关于《go语言打包的网页wasm示例详解》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于golang的内容请关注golang学习网公众号!

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>