”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 Gin 项目中启用热重载

如何在 Gin 项目中启用热重载

发布于2024-08-27
浏览:875

How to enable hot reload in your Gin project

Gin 是 Go 世界中最快的框架之一。然而,Gin 中缺少一项功能,那就是 hot realod。因此,在这篇博客中,我可以向您展示如何在 Gin 项目中启用热重载功能。

假设这是你的 main.go fie

package main

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

func successResponse(data interface{}) gin.H {
    return gin.H{
        "status": "success",
        "data": data,
    }
}

func successResponseWithMessageAndCode(data interface{}, message string, code int,c *gin.Context) {
    c.JSON(code, gin.H{
        "status": "success",
        "data": data,
        "message": message,
    })
}

func main() {
    r := gin.Default()
    fmt.Println("Hello World")
    r.GET("/", func(c *gin.Context) {
        data:= map[string]interface{}{
            "message": "Hello World",
        }
        successResponseWithMessageAndCode(data, "Success", http.StatusOK, c)
    })

    r.GET("/hello", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "Hello World",
        })
    })

    r.Run("localhost:8080")

}

所以我们可以使用 Air (https://github.com/air-verse/air) - 为您的 Go 应用程序实时重新加载

使用此命令安装Air?

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

然后使用此命令添加 .air.toml 文件

air init

如果找不到air命令,可能是因为Go bin目录不在你的PATH中

在这种情况下,我使用的是 Fish Terminal

首先,让我们找出 Go 安装二进制文件的位置。运行此命令:

echo $GOPATH/bin

如果没有设置$GOPATH,默认位置通常是~/go/bin。

现在,让我们将此目录添加到 Fish 中的 PATH 中。打开您的 Fish 配置文件:

nano ~/.config/fish/config.fish

将以下行添加到文件中:

set -gx PATH $PATH $GOPATH/bin

如果未设置$GOPATH,则使用完整路径,例如:

set -gx PATH $PATH ~/go/bin

保存文件并退出编辑器。
重新加载您的 Fish 配置:

 ~/.config/fish/config.fish

现在再次尝试运行空气:

air

如果您使用的是 bash 终端,则必须编辑 .~/bashrc 文件。

现在编辑.air.toml文件

root = "."
tmp_dir = "tmp"

[build]
cmd = "go build -o ./tmp/main ."
bin = "tmp/main"
full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
include_ext = ["go", "tpl", "tmpl", "html"]
exclude_dir = ["assets", "tmp", "vendor"]
include_dir = []
exclude_file = []
log = "air.log"
delay = 1000 # ms
stop_on_error = true
send_interrupt = false
kill_delay = 500 # ms

[log]
time = false

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

[misc]
clean_on_exit = true

确保您的 Gin 应用程序在本地主机上侦听,而不仅仅是 :8080 以获得更好的热重载行为

r.Run("localhost:8080")

现在不用运行 go run main.go ,只需运行 air 即可看到神奇的效果。

版本声明 本文转载于:https://dev.to/siumhossain/how-to-enable-hot-reload-in-your-gin-project-42g4?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3