Getting started with Go WebAssembly

WebAssembly can compile other languages ​​such as C/Go/Rust into wasm executable binary files, and then execute wasm through the browser.

This article takes the Go language as an example to introduce the introduction of WebAssembly.

1. Write the main.go file, get the js object in the Go code, and execute the js code.

Introduced syscall/jsto get the js object through js.Global().Get().
js.Global().Get()Both functions and DOM elements can be obtained. The type is js.Value.
Such as: js.Global().Get("alert")

package main

import (
	"fmt"
	"syscall/js"
)

func main() {
    
    
	fmt.Println("Hello, Go WebAssembly!")
    alert := js.Global().Get("alert")
    alert.Invoke("Hello, Go WebAssembly!")
}

2. Build main.go into a wasm binary file

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

3. Copy JavaScript dependencies to the current path

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

4. Create index.html, import wasm_exec.js, and call lib.wasm built in the second step

<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>

5. Create server.go to listen on port 8080 and serve the current path

package main

import (
        "net/http"
        "log"
)

func main() {
    
    
	err := http.ListenAndServe(":8080", http.FileServer(http.Dir(".")))
    log.Fatalln(err)
}

6. Start the service

go run server.go

browser access http://localhost:8080.
We can see that the browser console prints fmt.Println("Hello, Go WebAssembly!")output results. And the page pops up a pop-up window for go to call alert.
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45804031/article/details/127741426