<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicolas Lepage on Medium]]></title>
        <description><![CDATA[Stories by Nicolas Lepage on Medium]]></description>
        <link>https://medium.com/@nlepage?source=rss-6b43410827a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gp0HDjSBaGkLKTq9GO87JA.jpeg</url>
            <title>Stories by Nicolas Lepage on Medium</title>
            <link>https://medium.com/@nlepage?source=rss-6b43410827a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 13 Apr 2026 11:42:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nlepage/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Go WebAssembly: Binding structures to JS references]]></title>
            <link>https://medium.zenika.com/go-webassembly-binding-structures-to-js-references-4eddd6fd4d23?source=rss-6b43410827a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eddd6fd4d23</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[webassembly]]></category>
            <dc:creator><![CDATA[Nicolas Lepage]]></dc:creator>
            <pubDate>Fri, 06 Jul 2018 13:53:33 GMT</pubDate>
            <atom:updated>2018-07-11T08:46:32.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSFQsDTvRxI5G3_vPM55Xw.png" /></figure><p>Support for WebAssembly will be shipped with <a href="https://tip.golang.org/doc/go1.11">Go 1.11</a> (expected in august 2018), and with it the brand new syscall/js package.</p><p>The syscall/js package allows our Go code to interact with JS references, mainly through the js.Value type with methods such as Get(), Set() or Invoke().</p><p>I found myself wondering if there would be an easier way to manipulate JS references, and the struct tags were the first thing to come to my mind.</p><p>These are well known for their use in the encoding/json package and other packages such as ORM ones, to give hints as to how structs should be (un)marshalled:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e38cdacaec1e13ae12b2cb63848ba426/href">https://medium.com/media/e38cdacaec1e13ae12b2cb63848ba426/href</a></iframe><p>My idea was to use them to bind struct fields “directly” to JS references, without recurring explicitly to js.Value.</p><p>So I started building a small package to implement all the mechanics to bind JS references to a struct like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1b189584b590401e922b35613d67e6c/href">https://medium.com/media/d1b189584b590401e922b35613d67e6c/href</a></iframe><p>In this article I would like to share what I have done so far, how to use it, and how I did it.</p><p><strong>DISCLAIMERS:</strong></p><ul><li>I am not saying this is the right thing to do</li><li>This requires an extensive use of the reflect package hence brings some complexity</li><li>The package I’m presenting is incomplete, full of FIXMEs and TODOs, and may be buggy, it should be used for experimenting only</li></ul><p>This article follows my previous one about the syscall/js package API:</p><p><a href="https://medium.zenika.com/go-1-11-webassembly-for-the-gophers-ae4bb8b1ee03">Go 1.11: WebAssembly for the gophers</a></p><h3>Prerequisites</h3><p>In order to setup a working environment for building Go to WebAssembly and running it, please refer to my previous article linked above or other resources out there.</p><h3>Usage</h3><p>The package I made is available in the <a href="https://github.com/nlepage/golang-wasm/tree/master/js/bind">js/bind directory of my golang-wasm github repository</a>, you may download it with the following command:</p><pre>go get github.com/nlepage/golang-wasm/js/bind</pre><p>It offers only two public functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdeebda3832cb29ed7d367dca95c0199/href">https://medium.com/media/fdeebda3832cb29ed7d367dca95c0199/href</a></iframe><p>BindGlobals is just a helper to avoid calling Bind with js.Global as a parent.</p><p>Let’s take back our previous struct example…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1b189584b590401e922b35613d67e6c/href">https://medium.com/media/d1b189584b590401e922b35613d67e6c/href</a></iframe><p>… and make a small main function which increments counter and alerts a message with the current value of counter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7744014c0e6283df4db4cf6c8d58292b/href">https://medium.com/media/7744014c0e6283df4db4cf6c8d58292b/href</a></iframe><p>Nothing to do on the JS side, except declaring a count variable initialized to zero in the global scope:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a91d67b5d7681703a1293e109d060d31/href">https://medium.com/media/a91d67b5d7681703a1293e109d060d31/href</a></iframe><p>Now if we run the wasm binary several times without reloading the page, alert dialogs should appear with the current counter value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*aRwbyNCstRO8HjcKzZoq3Q.png" /></figure><p>The sources for a docker image with this alert counter are available in the <a href="https://github.com/nlepage/golang-wasm/tree/master/examples/bind-counter">examples/bind-counter directory of my github golang-wasm repository</a>.</p><p>As you could see in our example, Bind() handles three different kinds of binding:</p><ul><li>Functions</li><li>Getters</li><li>Setters</li></ul><h4>Functions</h4><p>In order to bind a JS function to a struct field, you have to declare a field typed func with the same signature as the JS function you want to bind.</p><p>In our previous example, <a href="https://mdn.io/Window/alert">window.alert()</a> has one string argument and has no return value, so the corresponding Go func type is func(string).</p><p>Then you have to tag the field with the identifier of JS function you want to bind, here alert, followed by () to indicate that it is not a property you want to bind but a function.</p><p>If we would like to bind <a href="https://mdn.io/parseInt">parseInt()</a> we could use the following structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a184bbe8ed1ea281de25e70e3c6b8881/href">https://medium.com/media/a184bbe8ed1ea281de25e70e3c6b8881/href</a></iframe><p>Once bound you may call it like a normal function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93e79598d7af56c8d1d36a44d8638700/href">https://medium.com/media/93e79598d7af56c8d1d36a44d8638700/href</a></iframe><p>The parenthesis following the name of the function in the tag are mandatory, without these Bind() could mistake the function for a getter or a setter.</p><h4>Getters</h4><p>In order to access the value of a JS reference, you need to bind a getter to this reference.</p><p>To bind a getter, you just have to declare a field typed func with no parameter and only one return value of the correct type (the return type may be one ofint, float64, bool or string).</p><p>Then tag the field with the identifier of the property you want to access, for example to access a global variable named message you may use the following struct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3d9761db671aceda2a69636aaa67a74/href">https://medium.com/media/c3d9761db671aceda2a69636aaa67a74/href</a></iframe><p>Getters also support struct return types, performing a recursive binding in this case, so you could access <a href="https://mdn.io/Window/location">window.location</a> with the following structures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d36ebd16c40e68835260e426e1d3ab6/href">https://medium.com/media/5d36ebd16c40e68835260e426e1d3ab6/href</a></iframe><p>Once bound you may read window.location.href with example.Location().Href().</p><h4>Setters</h4><p>In order to assign a value of a JS reference, you need to bind a setter to this reference.</p><p>To bind a setter, you just have to declare a field typed func with only one parameter of the correct type and no return value.</p><p>Then, like for getters, tag the field with the identifier of the property you want to assign.</p><h4>What could be added ?</h4><p>A lot more could be added to the current features supported by Bind(), including but non ehaustive:</p><ul><li>Handling struct typed parameters in functions and setters</li><li>Handling func typed parameters in functions and setters (dynamically creating callbacks)</li><li>Handling composed structures</li></ul><h3>Under the hood</h3><p>In order to interpret struct tags we must use the reflect package of the standard library.</p><p>The struct tags are accessible on the reflect.StructField of the different fields which can be retrieved on the reflect.Type of the struct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bbced5e334a96e79e36c94d0d8170df/href">https://medium.com/media/4bbced5e334a96e79e36c94d0d8170df/href</a></iframe><p>Then the struct tags can be accessed via the Tag field of the reflect.StructField:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/861b9eed6e358c795b177dbea11e0965/href">https://medium.com/media/861b9eed6e358c795b177dbea11e0965/href</a></iframe><p>Now using the hints given by the tags we have to dynamically assign functions to the struct fields.</p><p>Again this is going to require some reflect black magic in order to “build” function values with the correct signature.</p><p>A getter (or a setter) signature is rather easy to satisfy, here is an example of how to make a reflect.Value of an int getter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/176959dc92b44e9fc08dcbaf657b3f4b/href">https://medium.com/media/176959dc92b44e9fc08dcbaf657b3f4b/href</a></iframe><p>Then we can assign it to the struct field using the reflect.Values of the struct and fields:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60dae20b33b27d38f15835de9e4462b7/href">https://medium.com/media/60dae20b33b27d38f15835de9e4462b7/href</a></iframe><p>Building a reflect.Value matching an arbitrary signature is a little more tricky, it can be done using reflect.MakeFunc() and giving reflect.Type.</p><p>If you want to go further, have a look at the sources in the <a href="https://github.com/nlepage/golang-wasm/tree/master/js/bind">js/bind directory of my golang-wasm github repository</a>, and why not fork it and make it a real package?</p><p>Thank you for reading, have fun !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eddd6fd4d23" width="1" height="1" alt=""><hr><p><a href="https://medium.zenika.com/go-webassembly-binding-structures-to-js-references-4eddd6fd4d23">Go WebAssembly: Binding structures to JS references</a> was originally published in <a href="https://medium.zenika.com">Zenika</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go 1.11: WebAssembly for the gophers]]></title>
            <link>https://medium.zenika.com/go-1-11-webassembly-for-the-gophers-ae4bb8b1ee03?source=rss-6b43410827a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae4bb8b1ee03</guid>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Nicolas Lepage]]></dc:creator>
            <pubDate>Wed, 20 Jun 2018 07:10:50 GMT</pubDate>
            <atom:updated>2019-01-15T06:56:32.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzE0j8x2FurAB0hkwENFlw.png" /></figure><p>In February 2017, the <a href="https://github.com/golang/go/issues/18892">issue for WebAssembly support</a> was opened at golang/go by <a href="https://medium.com/u/35f4646b3348">Brad Fitzpatrick</a> member of the Go team.</p><p>Four months later, <a href="https://medium.com/u/1b34f20489ee">Richard Musiol</a>, author of GopherJS, enters the discussion with some “naive” ideas on how to add WebAssembly as a new target for Go compiler… finally posting a “fyi: I have started implementing this” in early November 2017.</p><p>Finally the issue was closed in June 2018, and the brand new support for the WebAssembly target merged in the <a href="https://github.com/golang/go">golang/go repository</a>’s master branch then released with <a href="https://golang.org/doc/go1.11#wasm">Go 1.11</a> in August 2018.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*li21rVa1mGQKG46Bislq6w.png" /></figure><p>This is the occasion to mix two of my favorite languages, let’s take a peek at what we can do with this first implementation!</p><p>All the examples shown in this article may be easily run using the image tagged examples from <a href="https://hub.docker.com/r/nlepage/golang_wasm/">nlepage/golang_wasm</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KuEuMqvg8oCTzcIPfO5UA.png" /></figure><p>Then visit <a href="http://localhost:32XXX/">http://localhost:32XXX/</a> and follow the links to the examples.</p><p>⚠ <strong>Warning! As of February 2019 and the release of Go 1.12, this article will be/is outdated:</strong></p><ul><li>js.Callback is renamed to js.Func, js.NewCallback() to js.FuncOf() (js.NezEventCallback() is deleted)</li><li>Callbacks are now executed synchronously, and support a return value</li></ul><h3>Hello Wasm!</h3><p>Making a basic hello world has already been covered by some really good articles out there, so let’s just go over it quickly.</p><p>The first thing you need is an up to date Go toolkit (1.11 or higher). You may also use a docker image from the <a href="https://hub.docker.com/r/_/golang/">official Go repository</a>.</p><p>Now you can write a traditional helloworld.go and compile it with the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ax286d96MXkwmz_vvTYlwA.png" /></figure><p>You may also use a Dockerfilelike this to compile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZF40hD23DOeKV6fUVpSJg.png" /></figure><p>The final step consists in using the wasm_exec.html and wasm_exec.js files, available in <a href="https://github.com/golang/go/tree/master/misc/wasm">golang/go’s </a><a href="https://github.com/golang/go/tree/master/misc/wasm">misc/wasm directory</a> of the toolkit, to execute test.wasm in the browser (wasm_exec.jsexpects the binary to be named test.wasm, that’s why we are using this name).</p><p>You just have to serve the 3 files, using nginx for example, then wasm_exec.html will display a “Run” button (enabled only if test.wasm has been loaded correctly).</p><p>Be warned that test.wasm has to be served with the application/wasm MIME type, otherwise the browser may refuse to load it (nginx for instance needs an <a href="https://github.com/nlepage/golang-wasm/blob/master/nginx/mime.types">updated </a><a href="https://github.com/nlepage/golang-wasm/blob/master/nginx/mime.types">mime.types file</a>).<br>You can use the image tagged nginx from <a href="https://hub.docker.com/r/nlepage/golang_wasm/">nlepage/golang_wasm</a>, which has the correct MIME type and already includes wasm_exec.html and wasm_exec.js in the /usr/share/nginx/html/ directory.</p><p>Now click the “Run” button, then open your browser’s console and you should see a console.log of your hello world (wasm_exec.js captures test.wasm&#39;s standard output and calls console.log for each new line).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*vMFBuYpc9UsNE2mieNLnHQ.png" /></figure><p>The sources for a docker image with this hello world are available in the <a href="https://github.com/nlepage/golang-wasm/tree/master/examples/hello">examples/hello directory of my github golang-wasm repository</a>.</p><h3>Calling JS from Go</h3><p>Now that we have successfully executed our first WebAssembly binary compiled from Go, let’s explore a little further the capabilities of this first implementation of Go’s wasm.</p><p>A new package syscall/js has made its entry in Go’s standard library, the first file to look at in there is <a href="https://github.com/golang/go/blob/master/src/syscall/js/js.go">js.go</a>.</p><p>A new type js.Value is available, which represents a JavaScript value.<br>It offers a simple API to manipulate and interact with any type of JavaScript value:</p><ul><li>js.Value.Get() and js.Value.Set() retrieve and set properties on an Object value</li><li>js.Value.Index() and js.Value.SetIndex() retrieve and set values in an Array value</li><li>js.Value.Call() calls a method on an Object value</li><li>js.Value.Invoke() invokes a function value</li><li>js.Value.New() invokes the new operator on a reference representing a JS type</li><li>Some more methods to retrieve a JavaScript value in its corresponding Go type such as js.Value.Int() or js.Value.Bool()</li></ul><p>And finally some interesting functions:</p><ul><li>js.Undefined() gives the js.Value corresponding to JS’s undefined</li><li>js.Null() gives the js.Value corresponding to JS’s null</li><li>js.Global() gives the js.Value giving access to JS’s global scope</li><li>js.ValueOf() which accepts any Go basic type and returns the corresponding js.Value</li></ul><p>Instead of sending the message to os.StdOut, let’s display it in an alert dialog using JS’s window.alert().</p><p>Since we are in a browser, the global scope is the window, hence the first thing we need to do is retrieve alert() from the global scope:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWPWq1qtObATxuxbR-ziDA.png" /></figure><p>Now we have a variable alert typed js.Value which is a reference to JS’s window.alert, we may use js.Value.Invoke()on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYs8fvLIwIhnEgkK5br34w.png" /></figure><p>As you can see, no need to call js.ValueOf() before handing the arguments to Invoke, it accepts a variadic of interface{}and runs the values through ValueOf for us.</p><p>Now our new program should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YaaLho0qzti63f_8aigTw.png" /></figure><p>As for our first hello world, we just need to build to a file named test.wasm, and we can reuse wasm_exec.html and wasm_exec.js as is.</p><p>Now when we click the “Run” button, an alert dialog with our message should show up.</p><p>The sources for a docker image with this “Go to JS” call are available in the <a href="https://github.com/nlepage/golang-wasm/tree/master/examples/js-call">examples/js-call directory of my github golang-wasm repository</a>.</p><h3>Calling Go from JS</h3><p>Calling JS from Go is pretty easy, now let’s explore some more syscall/js, a second file to look at is <a href="https://github.com/golang/go/blob/master/src/syscall/js/callback.go">callback.go</a>.</p><p>There is a new js.Callback type, which represents a Go func wrapped in order to be used as a JS callback.</p><p>There is also a new js.NewCallback() function which takes a func accepting a slice of js.Value (and returning nothing) and returns a js.Callback.</p><p>In there we also find some mechanic to manage the active callbacks, and a js.Callback.Release() which must be called when a callback won’t be used anymore in order to free up corresponding resources.</p><p>In addition there is a js.NewEventCallback() function to ease the reception of JS events.</p><p>Let’s try to do something simple: trigger a Go fmt.Println from the JS side.</p><p>The first thing we need to do is make some adjustments in wasm_exec.html, we have to be able to receive the callback from Go in order to call it.</p><p>First of all let’s add a text input, in order to be qble to custo;ize the messqge printed in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gn0cqVxTHmr5t3pl0ko97g.png" /></figure><p>For now the run() function that executes the wasm binary looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpMldAKgkGB0ZsLb6Eb_Xw.png" /></figure><p>It starts the wasm binary and waits for it to terminate, then it re-instantiates it for the next run.</p><p>Let’s adapt it in order to receive the Go callback before calling it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVwGM-qe6uP4OZ90OzJHTw.png" /></figure><p>Before executing the binary, we create a Promise for the callback reception, then after starting the binary, we wait for the Promise’s resolution before calling the callback.</p><p>Using the var keyword in the &lt;script&gt; element makes the setPrintMessage reference available in the global scope hence for the wasm binary.</p><p>And this is it on the JS part!</p><p>Now on the Go part, we need to create the callback, send it to the JS side and wait for it be called.</p><p>The first thing we need is a channel to notify that our callback has been called:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtoYW1uNZ2O3zFym67QDAA.png" /></figure><p>Then we have to write the actual printMessage() func:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1P4AXrv1JhRV3PmBoy5gxw.png" /></figure><p>As you can see the arguments are received in a slice of js.Value, so we have to call js.Value.String() on the first element of the slice in order to retrieve the message in a Go string.</p><p>Now we can wrap this func in a callback:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJDGFQY-EfWXqiAhb5uSQg.png" /></figure><p>Then invoke the JS setPrintMessage() function, exactly like when we called window.alert():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osoHMAX1L25TVTqynuXgfQ.png" /></figure><p>The last thing we need to do is wait for callback to be called:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fecrtunPJeD-xcKDjwH4Eg.png" /></figure><p>This last part is important because the callbacks are executed in a dedicated goroutine, hence the main goroutine has to wait for the callbacks to be called, otherwise the wasm binary will terminate prematurely.</p><p>The resulting Go program should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pf-GUE0aPU88ts1HdI8NzA.png" /></figure><p>As for our previous examples, we just need to build to a file named test.wasm, this time we have to replace wasm_exec.htmlby our version, and we can reuse wasm_exec.js as is.</p><p>Now when we click the “Run” button, as for our first example the message is printed in the browser’s console, but this time it is possible to customize it with the HTML input.</p><p>The sources for a docker image with this “JS to Go” call are available in the <a href="https://github.com/nlepage/golang-wasm/tree/master/examples/go-call">examples/go-call directory of my github golang-wasm repository</a>.</p><h3>Long running</h3><p>Calling Go from JS is a little more cumbersome than calling JS from Go, especially on the JS part.<br>This is partly because callbacks are executed asynchronously.</p><p>Let’s try something different: Why not have a wasm binary which will not terminate just after the callback is called, but will go on running and receive other calls?</p><p>This time let’s start on the Go side, like in our previous example we need to create a callback and send it to the JS side.<br>We are going to add a calls counter in order to keep track of how many times our callback has been called.</p><p>Our new printMessage() func is going to print the received message and the value of our calls counter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1Rb2iYZsTWFr9prbGDgqQ.png" /></figure><p>Creating the callback and sending it to the JS side is exactly the same as in our previous example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMU5xArr-Gb_xn3Pty52hA.png" /></figure><p>But this time we do not have the done channel to notify us when to terminate the main goroutine. One way could be to indefinitely block the main goroutine with and empty select:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0ycVIYywnoku-03urjJzg.png" /></figure><p>This is not very satisfying, our wasm binary will never shutdown cleanly and will likely be killed when wasm_exec.html is unloaded by the browser.</p><p>What we could do is listen for the beforeunload event of the page, we will need a second callback to receive the event and notify the main goroutine via a channel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWMBiOzsgdkFiBqNK-P6yQ.png" /></figure><p>This time so our new beforeUnload() func will take only one js.Value argument which is the event:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-kY9KGc6Y1JAuWG0UVuzg.png" /></figure><p>Then we can wrap it in a callback using js.NewEventCallback(), and register it to the JS side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUDY8SlBreGPOl6Q6EtC4g.png" /></figure><p>Finally we have to replace the empty select by a receive on the beforeUnloadCh channel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0BNjygZHLrWQ6LEYYesN_A.png" /></figure><p>Our final program should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiaSQ2FqKfZuDuJBt6-z7w.png" /></figure><p>Now on the JS part, the loading of the wasm binary previously looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvosDqDko3HNOuJPmnjNrg.png" /></figure><p>Let’s adapt it in order to start the binary straight after its loading:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_AHVS_FGNzmYybxtCbQvA.png" /></figure><p>And we’ll replace our “Run” button by a button to trigger printMessage():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_3OoTdXgar4lrgl_Yu3xQ.png" /></figure><p>Finally this time we need a setPrintMessage() in order to store the callback which will be used several times:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w24KtmmL7o2Z0Vm6WJW1ig.png" /></figure><p>Now when we click on the “Print message” button, we should see the message of our choice and the calls counter printed in the browser’s console.</p><p>Then if you check the “Preserve log” option of your browser’s console and trigger a refresh of the page, you should see the “Bye Wasm!” message in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8kKjEblLZFo_nccAmO7Mw.png" /></figure><p>The sources for a docker image with this are available in the <a href="https://github.com/nlepage/golang-wasm/tree/master/examples/long-running">examples/long-running directory of my github golang-wasm repository</a>.</p><h3>More to explore…</h3><p>As you can see, the syscall/js API we have explored goes straight to the point, and manages our simple examples with rather few code.<br>An easier interoperability between JS and Go functions would be welcome, if you would like to see my try at simplifying the Go -&gt; JS interoperability have a look at:</p><p><a href="https://medium.com/@nlepage/go-webassembly-binding-structures-to-js-references-4eddd6fd4d23">Go WebAssembly: Binding structures to JS references</a></p><p>For now the Go callbacks have no return values, so it’s not possible to return a value to JS directly from a Go function.<br>One warning about the callbacks: these are all executed in the same goroutine, so if you are making some blocking operations in a callback don’t forget to create a new goroutine of your own, otherwise you will block any other callback execution.</p><p>All the core features of the language are already available, including concurrency. For now all our goroutines will run in a single thread, but this might change in the future.</p><p>In our examples we only used the fmt package from the standard library, but a much larger part is available.<br>I have not dug into the file system support, but it seems that it is supported through Node.JS.</p><p>Finally what about performance? It would be interesting to run some benchmarks in order to see how Go wasm compares to equivalent pure JS code.</p><p>Thank you for reading, have fun!</p><p>Published: 20 June 2018<br>Last updated: 15 January 2019</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae4bb8b1ee03" width="1" height="1" alt=""><hr><p><a href="https://medium.zenika.com/go-1-11-webassembly-for-the-gophers-ae4bb8b1ee03">Go 1.11: WebAssembly for the gophers</a> was originally published in <a href="https://medium.zenika.com">Zenika</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>