air能够实时监听项目的代码,在代码发生更变之后自动重新编译并执行
安装air(windows)(1)、在https://github.com/cosmtrek/air/releases处可以下载air,放其入go的安装目录下的bin目录,重命名为air.exe
(2)、在windows命令窗口下,也可以使用curl -flo air.exe https://git.io/windows_air命令来安装air(访问外网,可启用go module, 设置go proxy进行加速)
安装后,我们可以在goland内置的命令行终端使用air -v命令检查是否安装成功:
使用并测试air通过air命令启用air
运行如下代码:
package mainimport ( fmt net/http)func handlerfunc(w http.responsewriter, r *http.request) { fmt.fprint(w, <h1>air自动重载<h1>)}func main(){ http.handlefunc(/, handlerfunc) http.listenandserve(:3030, nil)}
浏览器中访问localhost:3030/ 显示
修改代码
package mainimport ( fmt net/http)func handlerfunc(w http.responsewriter, r *http.request) { fmt.fprint(w, <h1>air自动重载<h1>)}func main(){ http.handlefunc(/, handlerfunc) http.listenandserve(:3000, nil)}
分别访问localhost:3030/ 、 localhost:3000/ ,效果如下:
代码版本使用命令查看文件状态:
$ git status
不难发现在项目根目录中出现 tmp 目录,该目录是air编译文件的存放地。我们需要设置版本控制器将tmp目录排除在外。
在根目录中新建一个.gitignore文件,该文件指示 git 在您进行提交时要忽略哪些文件和目录。创建后,将tmp目录添加到.gitignore文件:
此时,我们再使用命令查看文件状态就能发现,tmp目录被排除在外:
以上便是air自动重载在go项目中的使用。
以上就是详解使用air自动重载代码的详细内容。
