跳到主要内容

使用 Air 进行热重载的示例

Github StackBlitz

此示例演示如何使用 Air 工具为 Go 应用程序设置热重载。此示例的目的是展示如何在开发过程中随时更改源代码时自动重新加载应用程序。

描述

热重载是开发过程中非常有用的功能,因为当检测到更改时,它可以自动重新启动应用程序,从而节省时间。此示例设置了一个简单的 Fiber 应用程序,并配置 Air 来监视更改并重新加载应用程序。

要求

设置

  1. 克隆仓库

    git clone https://github.com/gofiber/recipes.git
    cd recipes/air
  2. 安装依赖

    go mod download
  3. 安装 Air

    go install github.com/air-verse/air@latest

配置

Air 使用 air/.air.conf 文件进行配置。此文件指定构建命令、二进制名称以及要监视更改的目录。提供了不同操作系统的配置文件

  • air/.air.windows.conf (适用于 Windows)
  • air/.air.linux.conf (适用于 Linux)

运行示例

要运行具有热重载的示例,请使用以下命令

air -c .air.linux.conf

或对于 Windows

air -c .air.windows.conf

服务器将启动并监听 localhost:3000。对源代码的任何更改都将自动触发应用程序的重建和重启。

示例路由

  • GET /:返回一个简单的问候消息。

代码概览

main.go

package main

import (
"log"
"github.com/gofiber/fiber/v2"
)

func main() {
// Create new Fiber instance
app := fiber.New()

// Create new GET route on path "/"
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})

// Start server on http://localhost:3000
log.Fatal(app.Listen(":3000"))
}

结论

此示例提供了使用 Air 热重载 Go 应用程序的基本设置。可以进一步扩展和定制以适应更复杂应用程序的需求。

参考资料