Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save elsanussi-s-mneina/1ffc6a98368ff714a5e92d1c178c18f8 to your computer and use it in GitHub Desktop.
Save elsanussi-s-mneina/1ffc6a98368ff714a5e92d1c178c18f8 to your computer and use it in GitHub Desktop.
I finally figured out how to call Go programming language code from Javascript when using GopherJS. This is a minimal working example.
This was done using GopherJS version numbers: GopherJS 1.17.1+go1.17.3
Date: December 2021
How to use. Assuming you have GopherJS runing and on your path.
Put surround.go, and index.html in the same directory.
Run the following command from that directory:
GOOS=linux gopherjs build surround.go
Open the index.html file, press the button on the screen labelled "Surround". After you press the button,
a piece of text on the screen changes to "(h)" which is the return value from a function in surround.go file.
How does this work?
The trick is to use the js.Global().Set function to create a global variable that Javascript can access.
The second trick is to store the function as a value in a map from string to interface{}.
<html>
<head>
</head>
<body>
<h1>Example 1 of calling surround Javascript code</code>
<p id="exampleLabel">Example text</p>
<input type="button" id="surroundButton" value="Surround"
onClick="document.getElementById('exampleLabel').innerText = pet.Su('h')"/>
<script src="surround.js"></script>
</body>
</html>
package main
import (
"syscall/js"
)
func main() {
js.Global().Set("pet", map[string]interface{}{
"Su": Su,
})
}
func Su(text string) string {
return "(" + text + ")"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment