Go 热重载:使用 Air 改变你的开发流程

架构大师笔记
架构大师笔记
发布于 2024-08-16 / 29 阅读
0
0

Go 热重载:使用 Air 改变你的开发流程

在 Go 语言开发中,每次修改代码后都需要手动重启服务,这无疑是一件效率低下的事情。本文将介绍一款名为 Air 的工具,它可以帮助我们实现 Go 代码的热重载,从而极大地提升开发效率。

手动重启的烦恼

假设我们有一个运行中的 Go 程序,例如:

go run main.go

该程序可能使用 fsnotify 来监听配置文件的变化,例如 config.json

{
  "db_host": "localhost",
  "db_user": "user"
}

当我们修改配置文件时,fsnotify 会检测到变化并应用新的配置。然而,如果我们修改了代码本身,就必须手动停止并重启程序才能使修改生效。这种方式不仅繁琐,而且效率低下。

Air:Go 热重载的利器

Air 是一款专门为 Go 语言设计的热重载工具,它可以监听项目文件变化,并在代码修改后自动重新编译并重启程序,从而避免手动操作。

安装 Air

使用以下命令即可轻松安装 Air:

go get -u github.com/cosmtrek/air

使用 Air

在项目根目录下创建一个名为 .air.toml 的配置文件,并添加以下内容:

# .air.toml
# Working directory
root = "."
tmp_dir = "tmp"

[build]
# Just plain old `go build` command. You probably want to add `-o tmp/main`
# to specify the output binary path
cmd = "go build -o ./tmp/main ."
# Binary file to run built project
# .air.toml will be searched in the current directory and up to 5 levels above.
bin = "tmp/main"
# Customize watch patterns.
# For example, exclude all test files from being watched.
[build.args]
  -v

# Watch these files or directories for changes.
# It accepts regular expressions.
[watcher]
# When a file changes, it will be rebuilt.
patterns = [
  "*.go",
  "*.tmpl",
  "*.html",
  "config/*",
]
# This log file will be rotated based on the value of `log.max_size`
log = "air.log"
# It accepts the unit of data size such as B, KB, MB, GB, etc.
log_max_size = "100MB"

# Optional: Customize success/error message.
[misc]
# The following colors can be used:
#   black, red, green, yellow, blue, magenta, cyan, white, default
#
# More color can be found at:
#   https://github.com/logrusorgru/aurora
success_msg_color = "green"
error_msg_color = "red"

在上述配置文件中,我们指定了项目的根目录、构建命令、二进制文件路径以及需要监听的文件类型。

运行 Air

在项目根目录下执行以下命令即可启动 Air:

air

Air 会启动程序并在后台监听文件变化。当我们修改代码并保存后,Air 会自动重新编译并重启程序,并在控制台输出相关信息。

Air 的优势

使用 Air 进行 Go 热重载具有以下优势:

  • 提升开发效率: 无需手动重启服务,代码修改后立即生效,大大节省开发时间。
  • 简化开发流程: 只需运行 Air,即可自动完成代码编译、重启等操作,降低开发复杂度。
  • 易于配置: 通过简单的配置文件即可定制 Air 的行为,满足不同项目的需求。

总结

Air 是一款功能强大的 Go 热重载工具,它可以帮助我们告别手动重启服务的烦恼,提高开发效率。如果你正在使用 Go 语言进行开发,强烈推荐尝试使用 Air 来优化你的开发流程。


评论