Go应用程序的条件构建、交叉编译与容器化部署
立即解锁
发布时间: 2025-09-14 00:08:03 阅读量: 1 订阅数: 34 AIGC 

# Go应用程序的条件构建、交叉编译与容器化部署
## 1. 条件构建应用程序
### 1.1 准备工作
为了确保示例清晰易遵循,需将现有的Pomodoro应用程序复制到新的工作环境。具体操作如下:
```bash
$ cp -r $HOME/pragprog.com/rggo/persistentDataSQL/pomo $HOME/pragprog.com/rggo/distributing
$ cd $HOME/pragprog.com/rggo/distributing/pomo
```
由于使用了Go模块,切换到新目录后无需额外操作,Go模块会自动解析当前目录的模块。
### 1.2 添加依赖
要在Pomodoro应用中使用`notify`包发送通知,需在`pomo`子目录下的`go.mod`文件中添加依赖,并使用`replace`指令将包路径指向本地目录:
```go
module pragprog.com/rggo/interactiveTools/pomo
go 1.16
require (
github.com/mattn/go-sqlite3 v1.14.5
github.com/mitchellh/go-homedir v1.1.0
github.com/mum4k/termdash v0.13.0
github.com/spf13/cobra v1.1.1
github.com/spf13/viper v1.7.1
pragprog.com/rggo/distributing/notify v0.0.0
)
replace pragprog.com/rggo/distributing/notify => ../../distributing/notify
```
### 1.3 实现可选通知功能
为使通知功能可选,添加辅助函数`send_notification`。默认情况下,该函数调用`notify`发送通知;用户可通过提供`disable_notification`构建标签禁用此功能。
- **创建`notification_stub.go`文件**:
```go
// +build containers disable_notification
package app
func send_notification(msg string) {
return
}
```
- **创建`notification.go`文件**:
```go
// +build !containers,!disable_notification
package app
import "pragprog.com/rggo/distributing/notify"
func send_notification(msg string) {
n := notify.New("Pomodoro", msg, notify.SeverityNormal)
n.Send()
}
```
- **在`buttons.go`文件中调用`send_notification`函数**:
```go
start := func(i pomodoro.Interval) {
message := "Take a break"
if i.Category == pomodoro.CategoryPomodoro {
message = "Focus on your task"
}
w.update([]int{}, i.Category, message, "", redrawCh)
send_notification(message)
}
end := func(i pomodoro.Interval) {
w.update([]int{}, "", "Nothing running...", "", redrawCh)
s.update(redrawCh)
message := fmt.Sprintf("%s finished !", i.Category)
send_notification(message)
}
```
### 1.4 构建应用程序
- 不使用任何标签重新构建应用程序以启用通知:
```bash
$ go build
```
- 提供`disable_notification`或`containers`标签重新构建应用程序以禁用通知。
### 1.5 容器构建选项
为使应用程序更适合在容器中运行,需禁用SQLite集成,仅提供`inMemory`存储库。编辑相关文件的构建标签:
- `pomodoro/repository/inMemory.go`:
```go
// +build inmemory containers
```
- `pomodoro/repository/sqlite3.go`:
```go
// +build !inmemory,!containers
```
- `cmd/repoinmemory.go`:
```go
// +build inmemory containers
```
- `cmd/reposqlite.go`:
```go
// +build !inmemory,!containers
```
### 1.6 验证构建文件
使用`go list`命令验证特定构建中包含的文件:
```bash
$ go list -f '{{ .GoFiles }}' ./...
$ go list -tags=inmemory -f '{{ .GoFiles }}' ./...
$ go list -tags=containers -f '{{ .GoFiles }}' ./...
```
## 2. 交叉编译应用程序
### 2
0
0
复制全文
相关推荐









