Go 桌面应用实战 Wails Demo

Go 实战|使用 Wails 构建轻量级的桌面应用:仿微信登录界面 Demo

概述

本文探讨 Wails 框架的使用,从搭建环境到开发,再到最终的构建打包,本项目源码 GitHub 地址:https://github.com/mazeyqian/go-run-wechat-demo

前言

Wails 是一个跨平台桌面应用开发框架,他允许开发者利用 Go 的性能优势,并结合任何前端技术栈,如 ReactVueSvelte,来创建桌面应用。

对于桌面应用,Electron 长久以来一直是主流选择,他使用 Web 前端技术构建跨平台的桌面应用。然而,Electron 有着较大的内存占用和应用体积,这让 Wails 成为了轻量级的替代方案。

Wails 的显著优势:

  1. 更小的应用体积:Wails 编译的应用程序通常比 Electron 更小,这意味着更快的下载速度和启动时间,以及更低的运行时资源消耗。
  2. 原生性能:Go 提供了接近 C 语言的性能,这使得 Wails 应用能够更高效地运行,尤其是在处理并发任务和系统级操作时。
  3. 简化的构建过程:Wails 简化了构建过程,只需一条命令就可以将应用打包为可执行文件,无需额外的配置或依赖。
  4. 优秀的开发体验:和开发 Web 前端应用一样的实时改动反馈,并且可以在浏览器中开发桌面应用。
  5. 原生用户界面元素:Wails 支持使用系统原生的用户界面元素,提供一致的用户体验。
  6. 灵活的前端选择:可以选择开发者熟悉的任何前端框架来开发桌面应用。

Components of a Wails App

创建一个 Wails 项目

在开始创建 Wails 项目之前,需要确保系统中已经安装了 Go 和 Node.js,因为 Wails 依赖这两者来构建桌面应用。以下是安装 Wails 框架和创建新项目的步骤。

安装 Wails

go install github.com/wailsapp/wails/v2/cmd/wails@latest

验证安装结果:

wails version

也可以通过 wails doctor 来检查是否所有必要的依赖都已正确安装。

# Wails
# ...
# System
# ...
# Dependencies
# ...
# Diagnosis
# ...
SUCCESS  Your system is ready for Wails development!

我的本地开发版本:

# Version
Wails v2.6.0
Go v1.19.1
Node.js v16.19.0
npm v8.19.3

创建新项目

使用 Wails CLI 创建一个名为 go-run-wechat-demo 的新项目:

wails init -n go-run-wechat-demo -t react-ts

项目结构

项目结构

  • main.goapp.go:Go 应用程序,处理业务逻辑、数据管理和与前端的通信。
  • frontend:包含前端的所有代码,使用 React、Vue 或你选择的任何其他框架,负责用户界面和与用户的交互。
  • go.modgo.sum:Go 的模块依赖文件。
  • wails.json:Wails 项目的配置文件,定义了如何构建和打包应用。
  • build:用于存放构建后的应用程序和相关资源。

项目开发:仿微信登录界面

进入开发模式

进入项目根目录,输入并执行 wails dev 命令,首次执行会安装前后端依赖,执行成功后可以看到默认应用页面。

默认应用页面

并且可以在浏览器调试页面:

To develop in the browser and call your bound Go methods from Javascript, navigate to: http://localhost:34115

任何代码修改也都能够热更新:

1:42:21 PM [vite] hmr update /src/App.tsx

修改代码

窗口样式和布局

为了模仿微信登录界面,在 main.go 文件中,通过 Wails 框架的配置选项修改了应用程序窗口的尺寸 Width&Height、背景色 BackgroundColour 和标题 Title

main.go

func main() {
    // Create an instance of the app structure
    app := NewApp()

    // Create application with options
    err := wails.Run(&options.App{
        Title:  "WeChat",
        Width:  280,
        Height: 400,
        AssetServer: &assetserver.Options{
            Assets: assets,
        },
        BackgroundColour: &options.RGBA{R: 255, G: 255, B: 255, A: 1},
        OnStartup:        app.startup,
        Bind: []interface{}{
            app,
        },
    })

    if err != nil {
        println("Error:", err.Error())
    }
}

后端实现

本次 Demo 主要实现两个功能,登录和切换账号;这两个方法可以通过前端 JavaScript 调用。返回的字符串可以用于在 UI 中显示相应的状态消息给用户。在文件 app.go 中添加这两个方法。

// Log In Success
func (a *App) LogInSuccess(name string) string {
    return fmt.Sprintf("Welcome %s, You are logged in!", name)
}

// Switch Account Success
func (a *App) SwitchAccountSuccess() string {
    return "You have switched accounts!"
}

在 Wails 开发模式下,会自动将 Go 结构体转换为 TypeScript 模块。

// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT

export function LogInSuccess(arg1:string):Promise<string>;

export function SwitchAccountSuccess():Promise<string>;

前端实现

修改 frontend/src/App.tsx 文件,添加相关逻辑:

import {useState} from "react";
import logo from "./assets/images/logo-universal-w256.jpg";
import "./App.css";
import {LogInSuccess, SwitchAccountSuccess} from "../wailsjs/go/main/App";

function App() {
    const [resultText, setResultText] = useState("");
    const name = "除";
    const updateResultText = (result: string) => setResultText(result);

    function logIn() {
        LogInSuccess(name).then(updateResultText);
    }

    function switchAccount() {
        SwitchAccountSuccess().then(updateResultText);
    }

    return (
        <div id="App">
            <img src={logo} id="logo" alt="logo"/>
            <div id="result" className="result name">{resultText || name}</div>
            <button className="btn log-in" onClick={logIn}>Log In</button>
            <button className="btn switch-account" onClick={switchAccount}>Switch Account</button>
        </div>
    )
}

export default App

并且修改了 CSS 样式文件 frontend/src/App.css 来适配界面:

.btn {
    display: block;
    margin: 0 auto;
    padding: 0;
    text-align: center;
    border: none;
    font-size: 14px;
}

.log-in {
    width: 200px;
    height: 36px;
    line-height: 36px;
    color: #ffffff;
    background-color: hsla(148, 61%, 46%, 1);
    border-radius: 4px;
    margin-top: 70px;
}

.switch-account {
    background-color: #ffffff;
    color: rgb(89, 107, 144);
    margin-top: 22px;
}

此时界面如图:

界面

尝试操作 Log In:

Log In

尝试操作 Switch Account:

Switch Account

底部图标:

底部图标

打包应用

在项目根目录,运行 wails build 即可打包当前环境下的应用程序。但是在开发模式下,已经有了一些缓存文件,可以配合 -clean 来清理 build/bin 目录:

wails build -clean

打包 macOS App:

wails build -platform=darwin/amd64

打包 Windows 程序:

wails build -platform=windows/amd64

打包

使用 create-dmg 为 macOS 创建 .dmg 文件:

create-dmg WeChat.dmg WeChat.app

macOS

以上文件可以进入 Releases 页面查看:

https://github.com/mazeyqian/go-run-wechat-demo/releases/tag/v1.0.0

Releases

总结

Wails 框架提供了一种简洁而强大的方式,让开发者能够利用 Go 的性能优势和 Web 前端的灵活性,从而能够使用更高效、更轻量级的方法来构建跨平台的桌面应用。

版权声明

本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者后除和本文原始地址:https://blog.mazey.net/4499.html

(完)

发表评论

您的电子邮箱地址不会被公开。