When writing code you want a fast feedback loop on your changes in the code. Live reloading is one feature that can enable that in your coding process.
The purpose of live reloading is to have an automatic reload of your application when a source file of the application is being changed. This is a common tool if you are working with web front-end development, but still useful for other types of applications.
To enable live reloading in Go we will checkout the command tool, Air - Live reload for Go apps.
Air is yet another live-reloading command line utility for developing Go applications. Run
air
in your project root directory, leave it alone, and focus on your code.
We start with the installation.
go version
// go version go1.22.0 linux/amd64
go install github.com/cosmtrek/air@latest
Next up is to create an example application to play with.
mkdir air-example && cd $_
go mod init example/air
touch main.go
code .
Enter this simple application into the main.go
file.
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello Air!")
}
Now we can start air
by just typing air
in the terminal, be sure that you are in the root directory of the application.
This will start the application and prompt you with the text, Hello Air
.
If we now change the text in the given Println
argument to, Hello, Air!!
, and save the file, Air will automatically restart the application and print the new text.
So that is how it basically works. There is one problem when it comes to running CLI applications in Air, and that is when you want to use IO operations like Scanf
. Air do not support that now (at least in v1.51.0), but it has plans for that in a future release. However developing web applications and services work great with Air right now.
There is also possible to configure Air with a .air.toml
file, which can be created like this.
air init
More details about the file can be found here.
As you might have noticed, Air
creates a tmp
folder that holds the compiled version of the application. This is one of several things you can configure in the toml file.
Overall Air
is an easy tool to get started with and it's convenient to have your application restarted automatically, so give it a try.
Happy coding!
Top comments (3)
Thanks for sharing this! Always wondered if there was a live reload tool for golang
Air does not have client reload support either, which can be really useful when you're doing full stack developments... I work on htmx + golang.
I use air but found myself wanting client-side reload quite badly, so I made it for a project of mine
github.com/MPMcIntyre/go-again