Get the App
SLTechnology News&Howtos  ›  Development  › 

How to generate a wasm file using golang and execute it on a browser

Shulou Source: shulou.com Published: 2022-06-01 08:15:17 10月31日 Update

This article mainly explains "how to use golang to generate wasm files and execute them on the browser". The content in the article is simple and clear, and it is easy to learn and understand. please follow the editor's train of thought to study and learn "how to use golang to generate wasm files and execute them on the browser".

What is webassembly?

Webassembly is a binary format that can be supported in web browsers or V8 environments. For more information, you can check this answer.

Start

Need to upgrade go to version 1.11 first

Write go files that need to be compiled into wasm files

/ / main.go

Package main

Func main () {

Println ("Hello, WebAssembly!")

}

Execute the build command

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

Note that this command is executed under the mac or linux operating system. Under windows, the environment variable should be set and then the compile command should be executed.

$env:GOARCH= "wasm"; $env:GOOS= "js"

Go build-o test.wasm main.go

After the command is executed, the test.wasm file is generated, which is the binary file that can be run on the browser.

Add additional dependencies

Copy the wasm_exec.html and wasm_exec.js files under $(go env GOROOT) / misc/wasm/ to the current directory

Set up web server

/ / test.go

Package main

Import (

"flag"

"log"

"net/http"

"strings"

)

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)

Log.Fatal (http.ListenAndServe (* listen, http.HandlerFunc (func (resp http.ResponseWriter, req * http.Request) {

If strings.HasSuffix (req.URL.Path, ".wasm") {

Resp.Header (. Set ("content-type", "application/wasm")

}

Http.FileServer (http.Dir (* dir)) .ServeHTTP (resp, req)

})

}

Run the web service

Go run test.go

test

Open http://localhost:8080/wasm_exec.html in the browser and click the run button on the page to see the console printing Hello, WebAssembly!

So we can use go to write a program that can run in the browser.

How to use js

Using go's js library syscall/js

/ / main.go

Package main

Import "syscall/js"

Func sum (args [] js.Value) {

Var sum int

For _, val: = range args {

Sum + = val.Int ()

}

Println (sum)

}

Func registerCallbacks () {

Js.Global () .Set ("sum", js.NewCallback (sum))

}

Func main () {

C: = make (chan struct {}, 0)

Println ("Hello, WebAssembly!")

RegisterCallbacks ()

Tags: File browser browse generate command learn compile run binary content object that is button console environment page control service operating system two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Technology Docker vpn OPPO Reno