53

Go WebAssembly 入门(一)

 5 years ago
source link: https://studygolang.com/articles/18097?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

已经安装Go 1.11及以上版本。

Getting Started

编辑main.go

package main

import "fmt"

func main() {
    fmt.Println("Hello, Go WebAssembly!")
}

把main.go build成WebAssembly(简写为wasm)二进制文件

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

把JavaScript依赖拷贝到当前路径

cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .

创建一个index.html文件,并引入wasm_exec.js文件,调用刚才build的lib.wasm

<html>
    <head>
        <meta charset="utf-8">
        <script src="wasm_exec.js"></script>
        <script>
            const go = new Go();
            WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject).then((result) => {
                go.run(result.instance);
            });
        </script>
    </head>
    <body></body>
</html>

创建server.go监听8080端口,serve当前路径

package main

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

var (
  listen = flag.String("listen", ":8080", "listen address")
  dir    = flag.String("dir", ".", "directory to serve")
)

func main() {
  flag.Parse()
  log.Printf("listening on %q...", *listen)
  err := http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir)))
  log.Fatalln(err)
}

启动服务

go run server.go

在浏览器访问localhost:8080,打开浏览器console,就可以看到输出 Hello, Go WebAssembly!

reference


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK