"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Gin 프로젝트에서 핫 리로드를 활성화하는 방법

Gin 프로젝트에서 핫 리로드를 활성화하는 방법

2024-08-27에 게시됨
검색:934

How to enable hot reload in your Gin project

Gin은 Go 세계에서 가장 빠른 프레임워크 중 하나입니다. 그러나 Gin is hot realod에는 한 가지 기능이 누락되어 있습니다. 그래서 이 블로그에서는 Gin 프로젝트에서 핫 리로드 기능을 활성화하는 방법을 보여드리겠습니다.

이것이 귀하의 main.go 파일이라고 가정합니다.

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에 없기 때문일 수 있습니다.

그 경우에는 피쉬 터미널을 사용하고 있습니다.

먼저 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 대신 localhost에서 수신 대기하는지 확인하세요.

r.Run("localhost:8080")

이제 main.go를 실행하는 대신 air를 실행하고 마법을 확인하세요.

릴리스 선언문 이 기사는 https://dev.to/siumhossain/how-to-table-hot-reload-in-project-42g4?1에서 재 인쇄되었습니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3