Get started with Go writing webassembly

Source: Internet
Author: User

Golang WebAssembly Getting Started

Golang introduced WebAssembly support in version 1.11, which means that you can later use go to write a program that you can run in a browser, which is certainly bound by the browser sandbox environment.

1. Run Go1.1 code in the browser
package mainfunc main() {    println("Hello, WebAssembly!")}
1.2 Compiling

It must be go1.11.

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

A separate wasm file cannot be run directly and must be loaded into the browser.

mkdir testcp test.wasm testcp $GOROOT/misc/wasm/wasm_exec.{html,js} .
1.3.11 Test HTTP Server

Chrome does not support running Wasm in local files, so there must be an HTTP server

//http.gopackage mainimport (    "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)    })))}
1.3.2 Http.go
1.4 Effects

Open http://localhost:8080/wasm_exec.html in the browser, click the Run button, you can see the Hello, webassembly! string in the console

2. Run Wasm in node

This is more straightforward.

node wasm_exec.js test.wasm

You can see the Hello, webassembly! string in the console.

3. Other examples

You can see more examples in example.

3.1 Bouncy

3.2 Ranbow-mouse

Will follow the mouse to draw a rainbow pattern, pretty good

3.3 Bumpy

Can draw some custom shape, the shape is different, the landing effect is different. The ball will bounce and the triangle will not. But it's not bad, not deformed, that's not true.

Get started with Go writing webassembly

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.