Skip to content

Instantly share code, notes, and snippets.

@ww9
Last active September 1, 2020 19:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ww9/040cdfe5b177ac3b995443fdf62bb392 to your computer and use it in GitHub Desktop.
Save ww9/040cdfe5b177ac3b995443fdf62bb392 to your computer and use it in GitHub Desktop.
Simple GUI example using https://github.com/zserge/lorca. Shows Go<->Js communication. #go

GUI programs using Go and HTML/CSS/JS

Superior to similar solutions. Doesn't use electron or cgo. Easy communication between Go and Js. Can easily use libs like React, Vue and Angular.

This is a demo app using GUI library https://github.com/zserge/lorca which requires only Chrome and might even work with Firefox in the future.

package main
import (
"fmt"
"log"
"net/url"
"os/exec"
"time"
"github.com/zserge/lorca"
)
func main() {
ui, err := lorca.New("", "", 480, 320)
if execErr, ok := err.(*exec.Error); ok {
lorca.PromptDownload()
log.Fatalf("\nChrome could not be started. Do you have Chrome installed? %s\n", execErr)
} else if err != nil {
log.Fatalf("\nOps. Something went wrong while starting the application: %s", err)
}
defer ui.Close()
ui.Load("data:text/html," + url.PathEscape(`
<html>
<head><title>Calling Go from Js and Js from Go</title></head>
<body>
<h1>1 - Calling Go code from page's Javascript</h1>
<script>
function incrementFromGoCode(button) {
// add() exists in Js because we called ui.Bind("add", func(){}) in Go
add(parseInt(button.value), 1).then(function(valueFromGo){
button.value = valueFromGo;
});
}
</script>
Click to call Go: <input type="button" id="button1" value="0" onclick="incrementFromGoCode(this)">
<h1>2 - Calling Javascript from Go</h1>
<p>Value updated from Go: <span id="span1">0</span></p>
</body>
</html>`))
// Allows Js to call our Go function add()
ui.Bind("add", func(a, b int) int { return a + b })
// Calls Js to increment value in HTML every second
go func() {
for i := 0; ; i++ {
ui.Eval(fmt.Sprintf("document.getElementById('span1').innerHTML = %d;", i))
time.Sleep(1 * time.Second)
}
}()
<-ui.Done()
}
@ww9
Copy link
Author

ww9 commented Nov 15, 2018

Screenshot

image

@jmiahman
Copy link

jmiahman commented Apr 1, 2019

How would one exit the app via a button, can't seem to find any examples and if you kill the go process the window doesn't die with it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment