gin框架使用Air实时加载

  1. Air实时加载
    本章我们要介绍一个神器——Air能够实时监听项目的代码文件,在代码发生变更之后自动重新编译并执行,大大提高gin框架项目的开发效率。

1.1.1. 为什么需要实时加载?
之前使用Python编写Web项目的时候,常见的Flask或Django框架都是支持实时加载的,你修改了项目代码之后,程序能够自动重新加载并执行(live-reload),这在日常的开发阶段是十分方便的。

在使用Go语言的gin框架在本地做开发调试的时候,经常需要在变更代码之后频繁的按下Ctrl+C停止程序并重新编译再执行,这样就不是很方便。

1.1.2. Air介绍
怎样才能在基于gin框架开发时实现实时加载功能呢?像这种烦恼肯定不会只是你一个人的烦恼,所以我报着肯定有现成轮子的心态开始了全网大搜索。果不其然就在Github上找到了一个工具:Air[1]。它支持以下特性:

彩色日志输出
自定义构建或二进制命令
支持忽略子目录
启动后支持监听新目录
更好的构建过程
1.1.3. 安装Air
go get -u github.com/cosmtrek/air

注意:windows下,下面的推荐方法有时会不自动重启,所以就不需要自己建文件,直接在根目录下输入air使用默认的配置文件即可,原因有待于研究

推荐的使用方法是:

1. 在项目根目录创建一个新的配置文件.air.conf

touch .air.conf

2. 复制 air_example.toml 中的内容到这个文件,然后根据你的需要去修改它

3. 使用你的配置运行 air, 如果文件名是 .air.conf,只需要执行 air

air

air_example.toml示例:如果是Macos或linux需要把full_bin配置项打开

# Config file for [Air](https://github.com/cosmtrek/air) in TOML format

# Working directory
# . or absolute path, please note that the directories following must be under root.
root = "."
tmp_dir = "tmp"

[build]
# Just plain old shell command. You could use `make` as well.
cmd = "go build -o ./main ."
# Binary file yields from `cmd`.
bin = "main"
# Customize binary, can setup environment variables when run your app.
# windows需要注释掉full_bin下面一行,否则会报错,参考链接:https://www.liwenzhou.com/posts/Go/live_reload_with_air/
# full_bin = "APP_ENV=dev APP_USER=air ./main"
# Watch these filename extensions.
include_ext = ["go", "tpl", "tmpl", "html"]
# Ignore these filename extensions or directories.
exclude_dir = ["assets", "tmp", "vendor", "frontend/node_modules"]
# Watch these directories if you specified.
include_dir = []
# Exclude files.
exclude_file = []
# Exclude specific regular expressions.
exclude_regex = ["_test.go"]
# Exclude unchanged files.
exclude_unchanged = true
# Follow symlink for directories
follow_symlink = true
# This log file places in your tmp_dir.
log = "air.log"
# It's not necessary to trigger build each time file changes if it's too frequent.
delay = 1000 # ms
# Stop running old binary when build errors occur.
stop_on_error = true
# Send Interrupt signal before killing process (windows does not support this feature)
send_interrupt = false
# Delay after sending Interrupt signal
kill_delay = 500 # ms

[log]
# Show log time
time = false

[color]
# Customize each part's color. If no color found, use the raw app log.
main = "magenta"
watcher = "cyan"
build = "yellow"
runner = "green"

[misc]
# Delete tmp directory on exit
clean_on_exit = true

Ari github链接

参考网站

posted @ 2021-12-14 11:12  专职  阅读(256)  评论(0编辑  收藏  举报