LoginSignup
27
13

More than 1 year has passed since last update.

Go + Air でホットリロード

Last updated at Posted at 2021-01-14

はじめに

Goでファイル変更したときにホットリロードさせるツールとして、
cosmtrek/airを使ってみたいと思います。

環境

go: v1.15.3

プロジェクト作成

% mkdir sample && cd sample
% go mod init sample

特にここはなんでも良いですが、フレームワークとしてginを使います。

% go get -u github.com/gin-gonic/gin
% vi main.go
package main

import "github.com/gin-gonic/gin"

func main()  {
  r := gin.Default()
  r.GET("/", func(c *gin.Context) {
    c.JSON(200, gin.H{
      "message": "レスポンス",
    })
  })

  r.Run()
}

go run

go runで起動してみます。

% go run main.go

立ち上がったら別のウィンドウで、

% curl http://localhost:8080
{"message":"レスポンス"}

airで動かす

導入

go get -u github.com/cosmtrek/air
% which air
<GOPATH>/go/bin/air

% air -v
  __    _   ___
 / /\  | | | |_)
/_/--\ |_| |_| \_ v1.12.1 // live reload for Go apps, with Go1.14.0

airが入ったら、go runのかわりにairコマンドで動かします。

$ air

起動したところでmain.goを書き換えます。

package main

import "github.com/gin-gonic/gin"

func main()  {
  r := gin.Default()
  r.GET("/", func(c *gin.Context) {
    c.JSON(200, gin.H{
      "message": "レスポンスだよ",
    })
  })

  r.Run()
}
% curl http://localhost:8080
{"message":"レスポンスだよ"}

ホットリロードできていました。

27
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
13