


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
go get
. After installation, you should use thewails setup
command to set it up.go get github.com/wailsapp/wails/cmd/wails wails setup
cpustats
:wails init
cd cpustats
Copy after login
Our project includes a Go backend and a Vue.js frontend. 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() }
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); })
wails build
, which can be done by adding the-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 }
mounted: function() {
wails.events.on("cpu_usage", cpu_usage => {
if (cpu_usage) {
console.log(cpu_usage.avg);
}
});
}
Copy after login
Measurement Barmounted: 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
That's it: npm install --save apexcharts
npm install --save vue-apexcharts
import VueApexCharts from 'vue-apexcharts' Vue.use(VueApexCharts) Vue.component('apexchart', VueApexCharts)
<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>
wails build -d ./cpustats
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.
