0、Air介绍

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

 

github地址:https://github.com/cosmtrek/air

 

1、安装

go install github.com/cosmtrek/air@latest

 

2、初始化

air init

 
默认生成配置文件.air.toml,内容如下:

root = "."
testdata_dir = "testdata"
# 日志存放位置
tmp_dir = "tmp"

[build]
  args_bin = []
  # 启动命令
  bin = "./tmp/main"
  # 编译
  cmd = "go build -o ./tmp/main ."
  delay = 1000
  exclude_dir = ["assets", "tmp", "vendor", "testdata"]
  exclude_file = []
  exclude_regex = ["_test.go"]
  exclude_unchanged = false
  follow_symlink = false
  full_bin = ""
  include_dir = []
  include_ext = ["go", "tpl", "tmpl", "html"]
  kill_delay = "0s"
  log = "build-errors.log"
  send_interrupt = false
  stop_on_error = true

[color]
  app = ""
  build = "yellow"
  main = "magenta"
  runner = "green"
  watcher = "cyan"

[log]
  time = false

[misc]
  clean_on_exit = false

[screen]
  clear_on_rebuild = false

按需修改日志、编译文件位置、编译后执行命令即可

 

3、准备服务

一个简单的demo

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	r := gin.Default()
	r.GET("/hello", func(c *gin.Context) {
		c.String(http.StatusOK, "mio")
	})
	_ = r.Run(":9090")
}

 

4、启动服务

air

请添加图片描述

此时监听9090端口

 

5、测试实时加载

将端口号9090改为9091后保存,看终端中是否重新编译

请添加图片描述

修改保存后服务重新编译启动,监听端口号变为了9091,测试成功

 
如有不对,烦请指出,感谢~

参考链接:
https://www.liwenzhou.com/posts/Go/live_reload_with_air/
https://blog.miuyun.work/archives/16036007

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐