LoginSignup
1
2

More than 1 year has passed since last update.

GolangでAirを使ってホットリロードを実現する

Last updated at Posted at 2021-09-11

realizeを愛用していましたが、開発が止まっているようなのでairを使ってホットリロードを実現します

環境

  • go version
    • 1.15.7

プロジェクト作成

$ mkdir go-hotreload-sample && cd go-hotreload-sample
$ go mod init go-hotreload-sample

フレームワークはサンプルとしてechoを使ってみます

$ go get github.com/labstack/echo/v4
main.go
package main

import (
  "net/http"
  "github.com/labstack/echo/v4"
  "github.com/labstack/echo/v4/middleware"
)

func main() {
  // Echo instance
  e := echo.New()

  // Middleware
  e.Use(middleware.Logger())
  e.Use(middleware.Recover())

  // Routes
  e.GET("/", hello)

  // Start server
  e.Logger.Fatal(e.Start(":8080"))
}

// Handler
func hello(c echo.Context) error {
  return c.String(http.StatusOK, "Hello, World!")
}

起動してみる

go runコマンドで起動してみます

$ go run main.go

ターミナルの別ウィンドウからリクエストを送ると、レスポンスが返ってくることを確認します

$ curl http://localhost:8080
Hello, World!

airでホットリロードを実現する

ダウンロード

$ go get -u github.com/cosmtrek/air

確認

$ air -v

  __    _   ___
 / /\  | | | |_)
/_/--\ |_| |_| \_ , built with Go

airが確認できたら、go runを使わずにairで起動します

air

以下のような感じで立ち上がることを確認します

⛄ air

  __    _   ___
 / /\  | | | |_)
/_/--\ |_| |_| \_ , built with Go

mkdir /path-to-dir/go-hotreload-sample/tmp
watching .
watching bin
!exclude tmp
building...
running...

   ____    __
  / __/___/ /  ___
 / _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.5.0
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                    O\
⇨ http server started on [::]:8080

起動できたことを確認したら、
main.goのレスポンス返却部分を変更してみます

// Handler
func hello(c echo.Context) error {
    return c.String(http.StatusOK, "hogehoge")
}

curlで再度確認します

$ curl http://localhost:8080
hogehoge

ホットリロードできていることを確認できました

参考

1
2
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
1
2