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
#!/bin/bash

# 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 -e moved_to --exclude '[^g][^o]$' $1 |
  while read line; do
    restart
  done
}

# Terminate and rerun the main Go program
function restart {
  if [ "$(pidof $PROCESS_NAME)" ]; then
    killall -q -w -9 $PROCESS_NAME
  fi
  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_PATH=$1
FILE_NAME=$(basename $FILE_PATH)
PROCESS_NAME=${FILE_NAME%%.*}

shift
ARGS=$@

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

# Monitor all /src directories on the GOPATH
OIFS="$IFS"
IFS=':'
for path in $GOPATH
do
  monitor $path/src &
done
IFS="$OIFS"

# If the current working directory isn't on the GOPATH, monitor it too
if [[ $PWD != "$GOPATH/"* ]]
then
  monitor $PWD
fi

wait

Usage

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

‚Äč