Home  >  Article  >  Backend Development  >  Example of building a desktop application using the Go Wails framework

Example of building a desktop application using the Go Wails framework

Guanhui
Guanhuiforward
2020-06-24 17:56:156186browse

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
Then let’s start our project with

cpustats

:

wails init
cd cpustats

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])),
    }
}
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()
}
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);
})
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
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);
        }
    });
}

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:

npm install --save apexcharts
npm install --save vue-apexcharts
Then import the

main.js### file:###
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: [&#39;CPU Usage&#39;]
      }
    };
  },
  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!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete