Go实战:使用Wails框架构建轻量级桌面应用
Go实战:使用Wails框架构建轻量级桌面应用
Wails是一个跨平台桌面应用开发框架,它允许开发者利用Go的性能优势,并结合任何前端技术栈(如React、Vue或Svelte)来创建桌面应用。与Electron相比,Wails具有更小的应用体积、更高的运行效率和更简化的构建过程。本文将通过一个仿微信登录界面的Demo,详细介绍如何使用Wails框架开发轻量级的桌面应用。
Wails框架简介
Wails框架具有以下显著优势:
- 更小的应用体积:Wails编译的应用程序通常比Electron更小,这意味着更快的下载速度和启动时间,以及更低的运行时资源消耗。
- 原生性能:Go提供了接近C语言的性能,这使得Wails应用能够更高效地运行,尤其是在处理并发任务和系统级操作时。
- 简化的构建过程:Wails简化了构建过程,只需一条命令就可以将应用打包为可执行文件,无需额外的配置或依赖。
- 优秀的开发体验:和开发Web前端应用一样的实时改动反馈,并且可以在浏览器中开发桌面应用。
- 原生用户界面元素: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.go和app.go:Go应用程序,处理业务逻辑、数据管理和与前端的通信。
- frontend:包含前端的所有代码,使用React、Vue或你选择的任何其他框架,负责用户界面和与用户的交互。
- go.mod和go.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
。
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:
尝试操作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
以上文件可以进入Releases页面查看:
https://github.com/mazeyqian/go-run-wechat-demo/releases/tag/v1.0.0
总结
Wails框架提供了一种简洁而强大的方式,让开发者能够利用Go的性能优势和Web前端的灵活性,从而能够使用更高效、更轻量级的方法来构建跨平台的桌面应用。