By default, when you do any changes to your go code, you need to re-build your binary to see the new changes. This is very annoying process and time consuming. To automate this process, you need a script to detect any changes in your working directory, and re-build the go app for you. Fortunately, There are many tools that do this for you. One of most popular tools is Air.
In this article, I will be demoing hot-reloading by building a simple go web application using docker and Air.
Prerequisites
- Golang
- Docker
- Docker compose
Steps
Create a new file called main.go and this code snippet
Create a new Dockerfile and install Air inside it. This docker file will be using later by docker-compose to provision a new container for application.
we simply use a latest docker image for golang, then we install Air. The entrypoint is air, which is the binary that responsible for watching your files and triggers the rebuild of your application.
You can configure Air command runtime, for example, you need to specify different option when you build your application. all these configuration can be specified in .air.conf file. This is a sample file.
Create you docker-compose file to create a docker container for your application
Now, you directory structure should be something like this
Now, you can start you application by running
docker-compose up
If you change any file in your application, Air will rebuild your app, you should see something like this.
Summery
Using Air and docker will help you. You don’t need to rebuild your application each time you do any change.
Thank you for reading :)