Home >Backend Development >Golang >Example of building a desktop application using the Go Wails framework
As we all know, Go is mainly used for building APIs, web backends and CLI tools. But what’s interesting is that Go can be used in places we didn’t expect.
This is a new framework, still in beta, but I was surprised how easy it is to develop and build applications.
Application
We are going to build a very simple application to display the CPU usage of my machine in real time. If you have the time and like Wails, you can come up with something more creative and complex.
Installation
wails setup
command to set it up.go get github.com/wailsapp/wails/cmd/wails wails setupThen let’s start our project with
cpustats
:wails init cd cpustats
main.go will be our entry point where we can include any other dependencies, along with the
go.mod
frontend
folder contains Vue.js components, webpack and CSS. ConceptThere are two main components used to share data between the backend and frontend: bindings and events.
In addition, Wails also provides a unified event system, similar to Javascript's local event system. This means that any event sent from Go or Javascript can be received by either party. Data can be passed along with any event. This allows you to do elegant things like have a background process run in Go and notify the frontend of any updates.
Backend
Let's first develop a backend part that gets the CPU usage and then sends it to the frontend using the
bind
pkg/sys/sys.go:
package sys import ( "math" "time" "github.com/shirou/gopsutil/cpu" "github.com/wailsapp/wails" ) // Stats . type Stats struct { log *wails.CustomLogger } // CPUUsage . type CPUUsage struct { Average int `json:"avg"` } // WailsInit . func (s *Stats) WailsInit(runtime *wails.Runtime) error { s.log = runtime.Log.New("Stats") return nil } // GetCPUUsage . func (s *Stats) GetCPUUsage() *CPUUsage { percent, err := cpu.Percent(1*time.Second, false) if err != nil { s.log.Errorf("unable to get cpu stats: %s", err.Error()) return nil } return &CPUUsage{ Average: int(math.Round(percent[0])), } }
If your struct has a
WailsInit method, Wails will call it on startup. This allows you to do some initialization before the main application starts.
Introduce the sys package in
main.go, bind the
Stats
package main import ( "github.com/leaanthony/mewn" "github.com/plutov/packagemain/cpustats/pkg/sys" "github.com/wailsapp/wails" ) func main() { js := mewn.String("./frontend/dist/app.js") css := mewn.String("./frontend/dist/app.css") stats := &sys.Stats{} app := wails.CreateApp(&wails.AppConfig{ Width: 512, Height: 512, Title: "CPU Usage", JS: js, CSS: css, Colour: "#131313", }) app.Bind(stats) app.Run() }Front end We bound the
stats
instance from Go, which can be calledwindow.backend.Stats on the front end. If we want to call the
GetCPUUsage()
window.backend.Stats.GetCPUUsage().then(cpu_usage => { console.log(cpu_usage); })To build the entire project into a single binary, we should run
-d flag to build a debuggable version. It will create a binary file with a name that matches the project name.
wails build -d ./cpustats
Event
We are using binding to send the CPU usage value to the frontend, now let's try a different approach, let's create a timer in the background which will be used in the background using the event method Send CPU usage value. We can then subscribe to the event in Javascript. In Go, we can do it in the WailsInit function:
func (s *Stats) WailsInit(runtime *wails.Runtime) error { s.log = runtime.Log.New("Stats") go func() { for { runtime.Events.Emit("cpu_usage", s.GetCPUUsage()) time.Sleep(1 * time.Second) } }() return nil }In Vue.js, we can do it when the component is mounted (or anywhere else) Subscribe to this event:
mounted: function() { wails.events.on("cpu_usage", cpu_usage => { if (cpu_usage) { console.log(cpu_usage.avg); } }); }
It would be nice to use a measurement bar to show CPU usage, so we will include a third party dependency and just use
npm That's it: npm install --save apexcharts
npm install --save vue-apexcharts
Then import the
import VueApexCharts from 'vue-apexcharts' Vue.use(VueApexCharts) Vue.component('apexchart', VueApexCharts)###Now we can use apexccharts to display the CPU usage and pass it from the backend Receive events to update the component's value: ###
<template> <apexchart></apexchart> </template> <script> export default { data() { return { series: [0], options: { labels: ['CPU Usage'] } }; }, mounted: function() { wails.events.on("cpu_usage", cpu_usage => { if (cpu_usage) { this.series = [ cpu_usage.avg ]; } }); } }; </script>###To change styles, we can modify ###src/assets/css/main### directly, or define them in the component. ######Finally, build and run###
wails build -d ./cpustats############Recommended tutorial: "###Go Tutorial###"###
The above is the detailed content of Example of building a desktop application using the Go Wails framework. For more information, please follow other related articles on the PHP Chinese website!