LoginSignup
6
3

More than 1 year has passed since last update.

GolangのホットリロードはAirを使おう

Posted at

はじめに

Go言語で開発時にライブリロード機能がないと毎回コンテナを落としてあげてが面倒だった。調べてみるとAirを導入するとライブリロードが使えるみたいなのでその導入方法をメモとして残しておきます。

FROM golang:1.18-alpine

RUN apk update &&  apk add git
RUN go install github.com/cosmtrek/air@v1.29.0
WORKDIR /app

CMD ["air", "-c", ".air.toml"]

上記の.air.toml公式のものを一旦そのまま持ってきています。カスタマイズしたい方は色々カスタマイズして見てください。

続いてdocker-compose.ymlは以下のように記述します。

version: '3.8'
services:
  server:
    build:
      context: ./server
      dockerfile: Dockerfile.server
    container_name: websocket_server
    ports:
      - "8080:8080"
    volumes:
      - ./server:/app

ライブリロードがちゃんと機能していることを確かめるためにサンプルファイルを配置します。

package main

import (
	"fmt"
	"net/http"
)

func say_hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, World!")
}

func main() {
	http.HandleFunc("/", say_hello)
	http.ListenAndServe(":8080", nil)
}

ここまでファイル構造は以下のようになっているはずです。

$ tree
.
├── README.md
├── docker-compose.yml
└── server
    ├── Dockerfile.server
    ├── go.mod 
    └── main.go
      
```shell
上記の状態でコンテナを起動し、以下のような画面になればAirの導入は完了です。
```shell
$ docker-compose build
$ docker-compose up server
docker-compose up server
[+] Running 1/1
 ⠿ Container websocket_server  Created                                     0.0s
Attaching to websocket_server
websocket_server  |
websocket_server  |   __    _   ___
websocket_server  |  / /\  | | | |_)
websocket_server  | /_/--\ |_| |_| \_ , built with Go
websocket_server  |
websocket_server  | mkdir /app/tmp
websocket_server  | watching .
websocket_server  | !exclude tmp
websocket_server  | building...
websocket_server  | running...

一旦Airの動作を確認しましょう。まずは上記の状態でlocalhost:8080にアクセスし、Hello, World!と表示されていることを確認します。

確認後にmain.goを編集し、Hello, World!Hello, abemaru!になっていればライブロードの設定が完了していることがわかります。

package main

import (
	"fmt"
	"net/http"
)

func say_hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, abemaru!") // ここを変更
}

func main() {
	http.HandleFunc("/", say_hello)
	http.ListenAndServe(":8080", nil)
}

ちなみに、ターミナルなどでairのログをみると、main.goが変更されていることをちゃんと検知していますね。

websocket_server  | main.go has changed
websocket_server  | building...
websocket_server  | running...

さいごに

ライブリロードがあると開発が捗るのでどんどん開発していこう

参考

6
3
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
6
3