Table of Contents
go get
wails build
Home Backend Development Golang Example of building a desktop application using the Go Wails framework

Example of building a desktop application using the Go Wails framework

Jun 24, 2020 pm 05:56 PM
go 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.

For example, we can build a desktop application with Go and Vue.js using the Wails framework.

This is a new framework, still in beta, but I was surprised how easy it is to develop and build applications.

Wails provides the ability to package Go code and web frontend into a single binary. Wails CLI makes this easy for you by handling project creation, compilation, and packaging.

ApplicationWe 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 CLI can be installed using

go get

. After installation, you should use the

wails setup

command to set it up.

go get github.com/wailsapp/wails/cmd/wails
wails setup
Copy after login
Then let’s start our project with

cpustats

:

wails init
cd cpustats
Copy after login

Our project includes a Go backend and a Vue.js frontend.

main.go will be our entry point where we can include any other dependencies, along with the go.mod

file to manage them.

frontend

folder contains Vue.js components, webpack and CSS.

Concept

There are two main components used to share data between the backend and frontend: bindings and events.

Binding is a single method that allows you to expose (bind) your Go code to the front end.

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. BackendLet's first develop a backend part that gets the CPU usage and then sends it to the frontend using the bind

method.

We will create a new package and define a type that I will expose (bind) to the frontend.

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])),
    }
}
Copy after login
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

instance and return it to the front end:

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()
}
Copy after login
Front end

We bound the

stats

instance from Go, which can be called

window.backend.Stats on the front end. If we want to call the GetCPUUsage()

function, it will return us a response.

window.backend.Stats.GetCPUUsage().then(cpu_usage => {
    console.log(cpu_usage);
})
Copy after login
To build the entire project into a single binary, we should run

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.

Let's test if it works by simply displaying the CPU usage value on the screen.

wails build -d
./cpustats
Copy after login
Copy after login
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
}
Copy after login
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);
        }
    });
}
Copy after login

Measurement Bar

Example of building a desktop application using the Go Wails framework 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:

Then import the

main.js### file:###
import VueApexCharts from 'vue-apexcharts'

Vue.use(VueApexCharts)
Vue.component('apexchart', VueApexCharts)
Copy after login
###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: [&#39;CPU Usage&#39;]
      }
    };
  },
  mounted: function() {
    wails.events.on("cpu_usage", cpu_usage => {
      if (cpu_usage) {
        this.series = [ cpu_usage.avg ];
      }
    });
  }
};
</script>
Copy after login
###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
Copy after login
Copy after login
############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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1263
29
C# Tutorial
1236
24
How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

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 pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

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.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

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.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

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.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

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,...

Golang framework development practical tutorial: FAQs Golang framework development practical tutorial: FAQs Jun 06, 2024 am 11:02 AM

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 provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

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, ...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

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.

See all articles