Golang Automatic Reloads

20th September 2013

I wrote a short Bash script to automatically reload Go programs.

The script acts as a light wrapper around go run, stopping and restarting it whenever a .go file in your current directory or $GOPATH/src folder is saved. I've been using it mainly when developing web applications, in the same way that I use Shotgun or Guard when working with Ruby.

You can grab this from the Github repository.

File: go-reload

# Watch all *.go files in the specified directory
# Call the restart function when they are saved
function monitor() {
  inotifywait -q -m -r -e close_write --exclude '[^g][^o]$' $1 |
  while read line; do

# Terminate and rerun the main Go program
function restart {
  if [ "$(pidof $PROCESS_NAME)" ]; then
    killall -q -w -9 $PROCESS_NAME
  echo ">> Reloading..."
  go run $FILE_PATH $ARGS &

# Make sure all background processes get terminated
function close {
  killall -q -w -9 inotifywait
  exit 0

trap close INT
echo "== Go-reload"
echo ">> Watching directories, CTRL+C to stop"

FILE_NAME=$(basename $FILE_PATH)


# Start the main Go program
go run $FILE_PATH $ARGS &

# Monitor the /src directories in all directories on the GOPATH
for path in $GOPATH
  monitor $path/src &

# Monitor the current directory
monitor .


The only dependency for this script is inotify-tools, which is used to monitor the filesystem for changes.

$ sudo apt-get install inotify-tools

Once you've downloaded (or copy-pasted) the script, you'll need to make it executable and move it to /usr/local/bin or another directory on your system path:

$ wget https://raw.github.com/alexedwards/go-reload/master/go-reload
$ chmod +x go-reload
$ sudo mv go-reload /usr/local/bin/

You should then be able to use the go-reload command in place of go run:

$ go-reload main.go
== Go-reload
>> Watching directories, CTRL+C to stop

If you found this post useful, you might like to subscribe to my RSS feed.

Filed under: golang