golang跨平台桌面应用开发插件库app的使用

Golang跨平台桌面应用开发插件库go-app使用指南

介绍

go-app是一个用于使用Go编程语言(Golang)和WebAssembly(Wasm)构建渐进式Web应用(PWA)的包。它使用声明式语法来创建和组合HTML元素,完全使用Go编程语言实现。

go-app图标

主要特性

  • 使用Go语言构建Web应用
  • 基于WebAssembly技术
  • 支持PWA特性
  • 声明式UI语法
  • 兼容Go标准HTTP包
  • 支持离线模式
  • SEO友好

安装要求

  • Go 1.18或更新版本
  • Go模块支持

安装命令:

go mod init
go get -u github.com/maxence-charriere/go-app/v10/pkg/app

声明式语法示例

下面是一个Hello World组件示例,它接收输入并在标题中显示输入值:

type hello struct {
	app.Compo  // 嵌入Compo基础结构体

	name string  // 组件状态
}

// Render方法定义组件UI
func (h *hello) Render() app.UI {
	return app.Div().Body(
		app.H1().Body(
			app.Text("Hello, "),
			app.If(h.name != "", func() app.UI {
				return app.Text(h.name)  // 如果有名字显示名字
			}).Else(func() app.UI {
				return app.Text("World!")  // 否则显示World!
			}),
		),
		app.P().Body(
			app.Input().
				Type("text").
				Value(h.name).
				Placeholder("What is your name?").
				AutoFocus(true).
				OnChange(h.ValueTo(&h.name)),  // 输入变化时更新name状态
		),
	)
}

标准HTTP集成

go-app应用兼容Go标准HTTP包接口:

func main() {
	// 组件路由:
	app.Route("/", func() app.Composer { return &hello{} })
	app.Route("/hello", func() app.Composer { return &hello{} })
	app.RunWhenOnBrowser()  // 在浏览器环境中运行

	// HTTP路由:
	http.Handle("/", &app.Handler{
		Name:        "Hello",
		Description: "An Hello World! example",
	})

	// 启动HTTP服务器
	if err := http.ListenAndServe(":8000", nil); err != nil {
		log.Fatal(err)
	}
}

完整示例DEMO

下面是一个完整的跨平台桌面应用示例:

package main

import (
	"log"
	"net/http"

	"github.com/maxence-charriere/go-app/v10/pkg/app"
)

// 定义主组件
type hello struct {
	app.Compo
	name string
}

// 渲染组件UI
func (h *hello) Render() app.UI {
	return app.Div().Body(
		app.H1().Body(
			app.Text("Hello, "),
			app.If(h.name != "", func() app.UI {
				return app.Text(h.name)
			}).Else(func() app.UI {
				return app.Text("World!")
			}),
		),
		app.P().Body(
			app.Input().
				Type("text").
				Value(h.name).
				Placeholder("What is your name?").
				AutoFocus(true).
				OnChange(h.ValueTo(&h.name)),
		app.Button().
			Text("Greet").
			OnClick(func(ctx app.Context, e app.Event) {
				if h.name == "" {
					app.Window().Call("alert", "Please enter your name!")
				} else {
					app.Window().Call("alert", "Hello "+h.name+"!")
				}
			}),
	)
}

func main() {
	// 组件路由配置
	app.Route("/", &hello{})
	app.Route("/hello", &hello{})
	app.RunWhenOnBrowser()

	// 创建HTTP处理程序
	handler := &app.Handler{
		Name:        "Hello",
		Description: "Greeting App",
		Styles: []string{
			`body {
				font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
				margin: 0;
				padding: 20px;
				text-align: center;
			}`,
		},
	}

	// 启动HTTP服务器
	if err := http.ListenAndServe(":8000", handler); err != nil {
		log.Fatal(err)
	}
}

构建和运行

  1. 将上述代码保存为main.go
  2. 初始化模块并获取依赖:
    go mod init hello-app
    go mod tidy
    
  3. 运行应用:
    go run .
    
  4. 在浏览器中访问 http://localhost:8000

打包为桌面应用

go-app应用可以打包为桌面应用,可以使用工具如:

文档

更多详细信息和高级用法,请参考官方文档。


更多关于golang跨平台桌面应用开发插件库app的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang跨平台桌面应用开发插件库app的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang跨平台桌面应用开发插件库App的使用

Go语言虽然主要用于服务端开发,但也可以用来开发跨平台桌面应用。以下是几个流行的Golang跨平台桌面应用开发框架及其使用方法。

1. Wails

Wails是一个流行的Go框架,允许使用Go后端和前端技术(如HTML/JS)构建桌面应用。

安装Wails

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

创建Wails项目

wails init -n MyApp -t svelte

基本结构

  • main.go: 主程序入口
  • frontend/: 前端代码
  • go.mod: Go模块文件

示例代码

package main

import (
	"embed"
	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
)

//go:embed frontend/dist
var assets embed.FS

func main() {
	app := NewApp()
	
	err := wails.Run(&options.App{
		Title:     "My App",
		Width:     1024,
		Height:    768,
		Assets:    assets,
		OnStartup: app.startup,
		Bind: []interface{}{
			app,
		},
	})
	
	if err != nil {
		println("Error:", err.Error())
	}
}

2. Fyne

Fyne是一个纯Go的UI工具包,用于构建跨平台应用。

安装Fyne

go get fyne.io/fyne/v2

简单示例

package main

import (
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
)

func main() {
	myApp := app.New()
	myWindow := myApp.NewWindow("Hello")
	
	hello := widget.NewLabel("Hello Fyne!")
	button := widget.NewButton("Click me", func() {
		hello.SetText("Welcome :)")
	})
	
	myWindow.SetContent(container.NewVBox(
		hello,
		button,
	))
	
	myWindow.ShowAndRun()
}

3. Lorca

Lorca使用Chrome/Chromium作为UI层,通过Go与前端交互。

安装Lorca

go get github.com/zserge/lorca

简单示例

package main

import (
	"log"
	"net/url"
	
	"github.com/zserge/lorca"
)

func main() {
	ui, err := lorca.New("", "", 480, 320)
	if err != nil {
		log.Fatal(err)
	}
	defer ui.Close()
	
	ui.Load("data:text/html," + url.PathEscape(`
		<!doctype html>
		<html>
			<body><h1>Hello, Lorca!</h1></body>
		</html>
	`))
	
	<-ui.Done()
}

4. Go-astilectron

结合Electron和Go来构建跨平台应用。

安装

go get github.com/asticode/go-astilectron
go get github.com/asticode/go-astilectron-bootstrap

简单示例

package main

import (
	"github.com/asticode/go-astilectron"
	"github.com/asticode/go-astilectron-bootstrap"
)

func main() {
	if err := bootstrap.Run(bootstrap.Options{
		AstilectronOptions: astilectron.Options{
			AppName:            "My App",
			AppIconDarwinPath:  "resources/icon.icns",
			AppIconDefaultPath: "resources/icon.png",
		},
		Windows: []*bootstrap.Window{{
			Homepage:       "index.html",
			MessageHandler: handleMessages,
			Options: &astilectron.WindowOptions{
				Center: astilectron.PtrBool(true),
				Height: astilectron.PtrInt(600),
				Width:  astilectron.PtrInt(800),
			},
		}},
	}); err != nil {
		panic(fmt.Errorf("running bootstrap failed: %w", err))
	}
}

func handleMessages(_ *astilectron.Window, m bootstrap.MessageIn) {}

比较

框架 特点 适合场景
Wails Go后端+任意前端技术 需要复杂前端交互的应用
Fyne 纯Go UI 简单UI的轻量级应用
Lorca 使用系统Chrome 快速原型开发
Go-astilectron 基于Electron 需要Electron生态的应用

打包发布

大多数框架都支持跨平台打包:

Wails打包

wails build -platform windows/linux/darwin

Fyne打包

fyne package -os windows -icon myapp.png

总结

Golang有多种方式开发跨平台桌面应用,选择取决于项目需求:

  • 需要丰富前端体验:Wails或Go-astilectron
  • 需要纯Go解决方案:Fyne
  • 快速原型开发:Lorca

所有框架都支持Windows、macOS和Linux三大平台,可以满足大多数桌面应用开发需求。

回到顶部