【Golang】修改代码后自动重新编译并启动

Posted by 西维蜀黍 on 2020-01-12, Last Modified on 2021-09-21

在开发 Go 的 Web 项目的过程中,让新增加或者修改的代码被自动编译并重启项目是一件可以提高工作效率的事情。

For Web Applications

Gin(https://github.com/codegangsta/gin)

$ go get github.com/codegangsta/gin

$ cd /home/project/myblog

$ gin

如果 main.go 文件不在根目录下,则通过 -d 来指定main.go 文件所在的文件夹

$ gin -d Gateway/main

这时控制台就开始编译打包执行了,注意控制台返回的信息,能知道项目的编译错误和日志,最后会有访问 url。

如果发现项目中有 go 文件新增或修改,gin 和 fresh 都会智能 reload 。

Air

Install

The classic way to install

$ go get -u github.com/cosmtrek/air

Usage

For less typing, you could add alias air='~/.air' to your .bashrc or .zshrc.

First enter into your project

$ cd /path/to/your_project

The simplest usage is run

# firstly find `.air.conf` in current directory, if not found, use defaults
$ air -c .air.conf

While I prefer the second way

# 1. create a new file
$ touch .air.conf

# 2. paste `air.conf.example` into this file, and **modify it** to satisfy your needs.

# 3. run air with your config. If file name is `.air.conf`, just run `air`.
$ air

air_example.conf

# 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 ./tmp/main main.go"
# Binary file yields from `cmd`.
bin = "tmp/main"
# Customize binary.
full_bin = "APP_ENV=dev APP_USER=air ./tmp/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 = []
# It's not necessary to trigger build each time file changes if it's too frequent.
delay = 1000 # ms
# Stop to run old binary when build errors occur.
stop_on_error = true
# This log file places in your tmp_dir.
log = "air_errors.log"

[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

For Other Applications - 使用 realize

$ go get github.com/oxequa/realize

Potential Error

$ go get github.com/oxequa/realize
go: finding github.com/oxequa/interact latest
go: finding golang.org/x/net latest
go: finding gopkg.in/urfave/cli.v2 v2.1.1
build github.com/oxequa/realize: cannot load gopkg.in/urfave/cli.v2: cannot find module providing package gopkg.in/urfave/cli.v2

$ go get gopkg.in/urfave/cli.v2@master
go: finding gopkg.in/urfave/cli.v2 master
go: finding gopkg.in master
$ GoPlayGround go get github.com/oxequa/realize    
$

Reference