1. 程式人生 > 實用技巧 >Go語言基礎之Gin框架的熱啟動

Go語言基礎之Gin框架的熱啟動

  • 我是很喜歡beego框架bee工具的熱啟動效果,感覺爽到不能呼吸。但是用gin框架去開發的時候,就發現難受的很~~
  • 所以,經過我在網上這頓搜,發現了一個好玩意兒,Air

Air是啥玩意兒啊?

這是一個能夠檢測專案程式碼變化的外掛,支援熱啟動,我一看,擦,想啥來啥!

Air的安裝

  1. go

    go get -u github.com/cosmtrek/air
    
  2. MacOS

    curl -fLo air https://git.io/darwin_air
    
  3. Linux

    curl -fLo air https://git.io/linux_air
    
  4. Windows

    curl -fLo air.exe https://git.io/windows_air
    
  5. Docker

    docker run -it --rm \
        -w "<PROJECT>" \
        -e "air_wd=<PROJECT>" \
        -v $(pwd):<PROJECT> \
        -p <PORT>:<APP SERVER PORT> \
        cosmtrek/air
        -c <CONF>
        
        
    # 然後按照下面的方式在docker中執行你的專案
    docker run -it --rm \
        -w "/go/src/github.com/cosmtrek/hub" \
        -v $(pwd):/go/src/github.com/cosmtrek/hub \
        -p 9090:9090 \
        cosmtrek/air
    

咋用啊?

  1. 為了一會兒爽,先把alias air='~/.air'這句新增到你的(也是我的).bashrc或者.zshrc中,別問,問就是為了一會兒爽!

  2. 進入你的專案目錄

    cd /path/to/your_project
    
  3. 在當前目錄建立一個新的配置檔案.air.conf

  4. 將下面這些內容複製到.air.conf配置檔案中,可以根據你的喜好去改

    # [Air](https://github.com/cosmtrek/air) TOML 格式的配置檔案
    
    # 工作目錄
    # 使用 . 或絕對路徑,請注意 `tmp_dir` 目錄必須在 `root` 目錄下
    root = "."
    tmp_dir = "tmp"
    
    [build]
    # 只需要寫你平常編譯使用的shell命令。你也可以使用 `make`
    # Windows平臺示例: cmd = "go build -o ./tmp/main.exe ."
    cmd = "go build -o ./tmp/main ."
    # 由`cmd`命令得到的二進位制檔名
    # Windows平臺示例:bin = "tmp/main.exe"
    bin = "tmp/main"
    # 自定義執行程式的命令,可以新增額外的編譯標識例如新增 GIN_MODE=release
    # Windows平臺示例:full_bin = "./tmp/main.exe"
    full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
    # 監聽以下副檔名的檔案.
    include_ext = ["go", "tpl", "tmpl", "html"]
    # 忽略這些副檔名或目錄
    exclude_dir = ["assets", "tmp", "vendor", "frontend/node_modules"]
    # 監聽以下指定目錄的檔案
    include_dir = []
    # 排除以下檔案
    exclude_file = []
    # 如果檔案更改過於頻繁,則沒有必要在每次更改時都觸發構建。可以設定觸發構建的延遲時間
    delay = 1000 # ms
    # 發生構建錯誤時,停止執行舊的二進位制檔案。
    stop_on_error = true
    # air的日誌檔名,該日誌檔案放置在你的`tmp_dir`中
    log = "air_errors.log"
    
    [log]
    # 顯示日誌時間
    time = true
    
    [color]
    # 自定義每個部分顯示的顏色。如果找不到顏色,使用原始的應用程式日誌。
    main = "magenta"
    watcher = "cyan"
    build = "yellow"
    runner = "green"
    
    [misc]
    # 退出時刪除tmp目錄
    clean_on_exit = true
    
  5. 直接在專案目錄下,執行air爽到不能呼吸!