Skip to content

Go语言实现开发环境代码热重载

前言

在go语言开发过程中,每修改一次代码就需要重新执行一次go run main.go命令,在开发调试过程中。这导致我们不断重复的工作,为了解决它,为了能让go语言在开发过程中能实现跟python一样的动态更新效果,出现了很多解决方案。热重载适合开发的过程中,生产环境不建议使用。

安装air

shell
go install github.com/cosmtrek/air@latest

安装完成后,你可能需要将GOPATH/bin添加到你的系统路径中,确保air命令可以在终端中全局调用。

创建air配置文件

在项目根目录创建一个名为air.toml的配置文件。以下是一个示例配置

[build]
cmd = "go build -o ./bin/main ./main.go"
bin = "bin/main"
full_bin = "./bin/main"
exclude_dir = ["assets", "tmp", "vendor"]
include_ext = ["go", "tpl", "tmpl", "html"]
exclude_ext = ["git", "swp"]
delay = 1000
kill_signal = "kill"
kill_timeout = 5
watch_log = true
color = true

这个配置文件会指示 air 监听 Go 源文件的更改,并在更改后重新编译和运行你的应用程序。

修改launch.json文件

修改launch.json文件,使其使用air进行调试。以下是个示例

json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Gin Application with Air",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${workspaceFolder}/bin/main",
            "preLaunchTask": "air",
            "env": {
                "GOPATH": "${workspaceFolder}"
            },
            "args": [],
            "showLog": true
        }
    ]
}

在这里我们将调试程序路径指向air生成的二进制文件

创建tasks.json文件

.vscode文件夹中创建一个tasks.json文件,用于定义启动air的任务。

json
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "air",
            "type": "shell",
            "command": "air",
            "isBackground": true,
            "problemMatcher": [
                {
                    "owner": "air",
                    "fileLocation": ["relative", "${workspaceFolder}"],
                    "pattern": [
                        {
                            "regexp": ".",
                            "file": 1,
                            "location": 2,
                            "message": 3
                        }
                    ],
                    "background": {
                        "activeOnStart": true,
                        "beginsPattern": ".",
                        "endsPattern": "."
                    }
                }
            ]
        }
    ]
}

使用热更新

完成以上配置后,你可以按照以下步骤进行调试

  1. 打开vscode并确保项目已经正确配置
  2. 在vscode左侧活动栏上选择调试图标
  3. 在上方的调试配置下拉列表中选择Launch Gin Application with Air
  4. 点击绿色的"启动调试"按钮(或按F5)启动调试

此时,air将会监视你的项目文件更改,并在保存文件后自动重新编译和运行你的应用程序。这样你就可以实现热更新功能。

Released under the MIT License.