Hot Reload in Golang Using Air - 07/04/2024
Hot reload in golang app while development using Air
Hot Reload in Golang Using Air
Prerequisites :
- Golang version 1.22 or higher
- I tested it on wsl2 in both windows and linux environment
Hot reload without docker container
-
Create a golang gin application
- Create a project directory and install gin-gonic :
go get -u github.com/gin-gonic/gin
- Now install Air :
go get -u github.com/cosmtrek/air
- Create a simple Gin application
// main.go package main import ( "github.com/gin-gonic/gin" ) func main() { // Create a new Gin router router := gin.Default() // Define a route router.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello, Gin!", }) }) // Run the server on port 8080 router.Run(":8080") }
-
initialize the
.air.toml
configuration file by running this commandair init
-
After this, you can just run the air command without additional arguments and it will use the .air.toml file for configuration.
air
Hot reload in docker container
-
We are going to use the above application. Create a
Dockerfile
with following content :FROM golang:1.22-alpine WORKDIR /app RUN go install github.com/cosmtrek/air@latest COPY go.mod go.sum ./ RUN go mod download CMD ["air", "-c", ".air.toml"]
-
Now create a
docker-compose.yaml
file :version: "3.8" services: web: build: context: . # Correct the path to your Dockerfile dockerfile: Dockerfile ports: - 8080:8080 # Important to bind/mount your codebase dir to /app dir for live reload volumes: - ./:/app
-
Now run
docker-compose up
and checklocalhost:8080
in browser. -
If your live reload is not working, try
poll = true
in .air.toml file and rebuild the docker image.