Golang 开发中的热加载工具

发布时间: 更新时间: 总字数:594 阅读时间:2m 作者: IP上海 分享 网址

Golang 热加载工具介绍,监听代码变更,自动编译并重新执行

介绍

  • 功能类似于 beego 的 bee 工具
  • 常见的工具

air

优点:

  • 彩色日志输出
  • 支持自定义构建或二进制命令
  • 允许忽略子目录
  • 启动后可继续监听新增目录
  • 优化了构建过程

安装

# 方式一
go install github.com/cosmtrek/air@latest

# 方式二
curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin

# 查看当前版本
air -v

基本使用

# 初始化配置文件 `.air.toml`
air init

# 启动服务
air
air -c .air.toml

# 传递参数,监听 8080 端口
air server --port 8080

air -- -h
air -c .air.toml -- -h

.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"]
  include_file = []
  kill_delay = "0s"
  log = "build-errors.log"
  poll = false
  poll_interval = 0
  post_cmd = []
  pre_cmd = []
  rerun = false
  rerun_delay = 500
  send_interrupt = false
  stop_on_error = false

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

[log]
  main_only = false
  time = false

[misc]
  clean_on_exit = false

[proxy]
  app_port = 0
  enabled = false
  proxy_port = 0

[screen]
  clear_on_rebuild = false
  keep_scroll = true

使用 vscode 远程调试

  • 重点配置参数
bin = "tmp/main.exe"
cmd = "go build -o ./tmp/main.exe {{项目路径}}"
full_bin = "{{dlv路径}} --listen=:{{监听端口}}--headless=true --api-version=2 --accept-multiclient exec tmp/main.exe"

# cmd = "go build -gcflags 'all=-N -l' -o ./tmp/main.exe ."
# full_bin = "dlv --listen=:2345 --headless=true --api-version=2 --continue --accept-multiclient exec tmp/main.exe"
# post_cmd = ["echo killing the dlv process.", "ss -lpn | grep LISTEN | grep 2345 | awk -F "pid=" '{print $2}' | awk -F "," '{print $1}' | xargs -I{} kill =9 {}", "echo kille success"]

说明:dlv 命令可以在 vscode 启动 golang 程序中看到,如是 dlv dap --listen=127.0.0.1:61875 --log-dest=3 时,在调试时,会自动注入 launch.json 中启动文件和环境变量等

go install github.com/go-delve/delve/cmd/dlv@latest
  • launch.json 配置
    "port": 2345,
    "host": "127.0.0.1",
  • 配置完成后,点击调试按钮
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数