Just “Air” in your projects
All of them are fast to develop since they take your changes when you just save the files you’re working on, same thing happens when you use something like express, there are tools like
nodemon that make this job easy.
In Go, there are multiple ways you can accomplish this. I’m gonna show one of them, the best one, in my opinion. I will also describe to you to do it with just the Go application, or with other dependencies in a docker-compose file.
This method works well with go modules. Also, if you add new dependencies with go get the app will be reloaded too.
This tutorial is divided into the following topics:
- Example go application (with go modules)
- Live-Reload single application
- Live-Reload with multiple dependencies (docker-compose)
This simple application consists of 2 files,
go.mod, it just prints a random number
uuid each time you press enter.
This simple program just generates a new UUID every 4 seconds and displays it in the console, easy enough to not distract us from the main objective: live-reload.
In order to get this application with live-reload (re-build and re-run on save) we need to install
go install github.com/cosmtrek/air@latest
This will install it directly from the Air repository. After that we can test the installation by running
Then we can go to our app directory and initialize it with:
This will create a file
.air.toml with default values. You can take a look at that and modify what you need for your application (build command, excluded folders, etc).
It will look something like this:
Having this initialized, we can start making use of the live-reload just running:
Now, if we make any changes to the application, It will detect it, compile it and run it. In this example, I just tested changing the number of seconds it waits for each UUID generation:
We can also archive the same, without installing air, through a docker container, just running it with the air docker image:
docker run -it — rm \
-w "/go/src/github.com/luisegr/go-live-reload-tutorial" \
-v $(pwd):/go/src/github.com/luisegr/go-live-reload-tutorial \
This will result in the same output and reload on changes:
If you are running your dev environment with docker-compose and you’re using other stuff like
postgres, mongo, Redis, etc. Together with your app, you can also make use of Air for your live reload.
You just need to set your
docker-compose.yml like this:
Then you can run your application as usual with:
You will see the output, and if you still have the live-reload feature:
I hope you find this useful, and for more details about all the features you can check the Air repository: