Dark Mode

5 Ways to Live Reloading Go Applications

live reloading go applications

Some people (including me) crave live reloading in Go, especially the ones who are used to working with interpreted languages like JavaScript, Python, and Ruby. This article covers 5 ways to live reloading Go applications.

This article assumes Go compiler is installed, and GOPATH/bin is added to PATH variable.

Before we get started, let’s create a simple web server that prints “Hello, World.”

package main

import (
	"net/http"
)

func main() {
	http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, World"))
	})

	http.ListenAndServe(":5000", nil)
}

Method 1: Using Air

Air is a command-line utility that provides live reloading for Go applications.

Install Air by running the following command.

go get -u github.com/cosmtrek/air

Next, create the Air configuration file .air.conf in the project’s root directory with the following configuration.

# .air.conf
# Config file for [Air](https://github.com/cosmtrek/air) in TOML format

# Working directory
# . or absolute path, please note that the directories following must be under root.
root = "." 
tmp_dir = "tmp"

[build]
# Just plain old shell command. You could use `make` as well.
cmd = "go build -o ./tmp/main ."
# Binary file yields from `cmd`.
bin = "tmp/main"
# Customize binary.
full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
# Watch these filename extensions.
include_ext = ["go", "tpl", "tmpl", "html"]
# Ignore these filename extensions or directories.
exclude_dir = ["assets", "tmp", "vendor", "frontend/node_modules"]
# Watch these directories if you specified.
include_dir = []
# Exclude files.
exclude_file = []
# It's not necessary to trigger build each time file changes if it's too frequent.
delay = 1000 # ms
# Stop to run old binary when build errors occur.
stop_on_error = true
# This log file places in your tmp_dir.
log = "air_errors.log"

[log]
# Show log time
time = false

[color]
# Customize each part's color. If no color found, use the raw app log.
main = "magenta"
watcher = "cyan"
build = "yellow"
runner = "green"

[misc]
# Delete tmp directory on exit
clean_on_exit = true

The configurations are self-explanatory, adjust them to suit your needs.

Finally, instead of running our Go application with the usual go run command, use the air command.

Method 2: Using Air Docker Image

This requires Docker. If you don’t have it installed already, you can install it by following the official documentation.

We are still going to be using Air, so the Air configuration file is still required. If you don’t have it already, go ahead and create one.

The Docker image cosmtrek/air comes with Air installed and Gopath set to /go.

We just need to mount our project folder into the Docker containers’ Gopath and expose the required ports. We can do it by running the docker run command like this:

docker run -it --rm -w <WORKING_DIR> -v <PROJECT_FOLDER>:<MOUNT_POINT> -p <HOST_PORT>:<CONTAINER_PORT> <IMAGE_NAME>

In my case, I had to run the following command:

docker run -it --rm -w /go/src/github.com/praveen001/live-reloading -v /go/src/github.com/praveen001/live-reloading:/go/src/github.com/praveen001/live-reloading -p 5000:5000 cosmtrek/air

Explanation:
Mount the project folder /home/praveen/go/src/github.com/praveen001/live-reloading in the container’s gopath /go/src/github.com/praveen001/live-reloading using the -v flag.

-v /home/praveen/go/src/github.com/praveen001/live-reloading:/go/src/github.com/praveen001/live-reloading 

Specify the mount point the same as the working directory using the -w flag.

-w /go/src/github.com/praveen001/live-reloading

The web server is listening at port 5000, so expose the container port 5000 to the host port 5000 using the -p flag.

-p 5000:5000

Finally, specify the docker image name cosmtrek/air.

Method 3: Using Gin

Gin is another command-line utility for live reloading Go applications.

Install Gin by running the following command.

go get github.com/codegangsta/gin

Instead of running the application using the usual go run main.go command, use the gin command.

In my case, the --appPort flag tells Gin that the application listens on port 5000, and --port flag tells Gin proxy to listen on port 3000.

gin --appPort 5000 --port 3000

Now, access the application using the Gin proxy http://localhost:3000.

If you want to exclude a certain folder from being watched, you can use the --excludeDir flag. Example:

gin --appPort 5000 --port 3000 --excludeDir ./frontend

If you want to use Gin for live reloading an application that doesn’t listen on any port, then you have to use the --immediate flag. But remember Gin will still try and listen on port 5000.

You can see all the supported flags on Gin’s Github repository.

Method 4: Use Nodemon

Nodemon is another command-line utility that was developed for live reloading Node applications. But it is possible to use it for live reloading any application by making use of the --exec flag.

This requires Nodejs and NPM to be installed. If you don’t have it, you can install it by following the Nodejs’s official documentation.

Install nodemon by running the following command:

npm install -g nodemon

Now, we can run the web server using Nodemon by running the following command:

nodemon --exec go run main.go --signal SIGTERM

If you want to configure Nodemon, create the configuration file nodemon.json in the project’s root directory. A full sample config file is available here.

Method 5: Use Fresh

Fresh is yet another Go based command-line utility for live reloading Go applications.

Install Fresh

go get github.com/pilu/fresh

Instead of running the application using the usual go run main.go command, use the fresh command.

fresh

For configuring Fresh, you can create a configuration file runner.conf in the project’s root directory.

Here is a sample configuration file.

root:              .
tmp_path:          ./tmp
build_name:        runner-build
build_log:         runner-build-errors.log
valid_ext:         .go, .tpl, .tmpl, .html
no_rebuild_ext:    .tpl, .tmpl, .html
ignored:           assets, tmp
build_delay:       600
colors:            1
log_color_main:    cyan
log_color_build:   yellow
log_color_runner:  green
log_color_watcher: magenta
log_color_app:

To Wrap Up

There are many other tools like:

that can be used to live reload Go applications. Just choose the one that suits your needs and keep enjoying developing Go applications.

Write the first response