Some caveats about the WebAssembly that Go is about to support

Source: Internet
Author: User
This is an instant record of webassembly, which is designed to give me a memo and not just a tutorial if you use it. The upcoming Go 1.11 release will support Wasm. @neelance did most of the work. Support for Wasm has been tested by his working branch on GitHub. See [This Article] (https://blog.gopheracademy.com/advent-2017/go-wasm/) For more information # # tool chain Setup to produce a wasm file from Go source, you need to get from the source and patch the Go tool Set: ' ' ~ mkdir ~/gowasm~ git clone https://go.googlesource.com/go ~/gowasm~ cd ~/gowasm~ git remote add neelance https://github . com/neelance/go~ git fetch--all~ git checkout wasm-wip~ cd src~./make.bash "Then use this version of Go to point Goroot to ~/gowasm and use ~/go Wasm/bin/go this binary file. # # The first example by convention, let's write a "Hello World": "Gopackage mainimport" FMT "Func Main () {FMT. Println ("Hello world!")} "' Then compile the file and name **example.wasm** ' ' goroot=~/gowasm goarch=wasm goos=js ~/gowasm/bin/go build-o example.wasm main.go ' # # Run This example this is an excerpt of the official document:> although there are plans to allow WebAssembly modules like the ES6 module (...) Load, but currently WebAssembly must be loaded and compiled by JavaScript, for basic loading, there are three steps to:> + to convert. Wasm bytes to an array or arraybuffer> + to compile bytes into Webassemly.modu le> + Use import instantiated Webassembly.module for callable export Fortunately, the Go author has provided a Javascript loader (~/Gowasm/misc/wasm/wasm_exec.js) to simplify the process. It comes with an HTML file that is responsible for pasting all the content in the browser. To actually run our files, you need to copy the following files into a directory and start as a Web service: ' ~ mkdir ~/wasmtest~ CP ~/gowasm/misc/wasm/wasm_exec.js ~/wasmtest~ CP ~/ gowasm/misc/wasm/wasm_exec.html ~/wasmtest/index.html~ CP example.wasm ~/wasmtest "Then edit this index.html file to run the correct example:" javascript//... Webassembly.instantiatestreaming (Fetch ("Example.wasm"), Go.importobject). then (result) = {mod = Result.module; Inst = Result.instance;document.getelementbyid ("Runbutton"). Disabled = false;}); /... ' Theoretically, any Web service can run it, but when we try to run it with caddy, we have a problem. This JavaScript loader requires the service to send this wasm file the correct MIME type to it. Here's a quick hack to run our tests: Write a Go service with special handling for our Wasm file. "' Gopackage mainimport (" Log "" Net/http ") Func Wasmhandler (w http. Responsewriter, R *http. Request) {W.header (). Set ("Content-type", "application/wasm") http. Servefile (W, R, "Example.wasm")}func Main () {mux: = http. Newservemux () Mux. Handle ("/", HTTP. Fileserver (http. Dir ("."))) Mux. Handlefunc ("/example.wasm", Wasmhandler) log. Fatal (http. Listenandserve(":", MUX))} ' * Note * Setting up a special router to handle all the Wasm files is no big deal, as I said, this is a POC, this article is just a note about it. Then use ' Go run Server.go ' to start the service and open the browser to access http://localhost:3000. Open the console and see! # # and browser interaction lets us interact with the world. # # # Solving the DOM problem the *syscall/js* package contains functions that allow interaction with the DOM through the JavaScript API. To get the documentation for this package, simply run: ' Goroot=~/gowasm godoc-http=:6060 ' and then access http://localhost:6060/pkg/syscall/js/with a browser. Let's write a simple HTML file to display an input box. Then from webassembly, we bind an event to this element and trigger an action when the event is heard. Edit the index.html and place the code under the Run button: "Html<button onclick=" Run (); "Id=" Runbutton "disabled>run</button>< Input type= "number" id= "MyText" value= ""/></body> "and then modify the Go file: ' gopackage mainimport ' FMT ' func main () {c: = m Ake (Chan struct{}, 0) cb = JS. Newcallback (func (args []js. Value) {move: = js. Global.get ("Document"). Call ("getElementById", "MyText"). Get ("value"). Int () fmt. PRINTLN (Move)}) JS. Global.get ("Document"). Call ("getElementById", "MyText"). Call ("AddEventListener", "input", CB)//The goal of the channel was to wait indefinitly//Otherwise, the main function en DS and The WASM modules stops <-c} "compile the file as before and refresh the browser ... Open the console and enter a number ... Look at the exposure function. This is a bit tricky ... I didn't find any simple way to expose a Go function to the Javascript ecosystem. What we need to do is create a Callback object in the Go file and assign it to a Javascript object. To get the results returned, we cannot return a value to callback instead of using a Javascript object instead. This is the new Go code: "' Gopackage mainimport (" Syscall/js ") func main () {c: = Make (chan struct{}, 0) Add: = Func (i []js]. Value) {js. Global.set ("Output", JS.) ValueOf (I[0]. Int () +i[1]. Int ()))}js. Global.set ("Add", JS. Newcallback (add)) <-c} "" Now compile and run the code. Open the browser and console. If you enter *output* will return *object not found*. Now you enter *add (2,3) * and *output* ... Should get 5. This is not an elegant way to interact, but it works as expected. # # Conclusion The go-to-wasm support has just begun, but is developing vigorously. Many features are now available to run. I can even run a full recursive neural network in the browser, thanks to Gorgonia. I will explain this later.

Via:https://blog.owulveryck.info/2018/06/08/some-notes-about-the-upcoming-webassembly-support-in-go.html

Author: parikshit agnihotry Translator: themoonbear proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

660 Reads

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.