Go: Automatically Run Tests or Reload Web Server on File Changes

Wouldn't it be convenient if you could automatically run your tests or reload your web server whenever you save your file. Here's a very simple way to achieve it. First download xnotify. Then run the following command in your project directory.

./xnotify -i . -- go test -c ./... -- ./test.test

That will automatically run your tests.

./xnotify -i . -- go build main.go -- ./main

That will automatically reload your web server.

What the command does is watch the current directory with -i . then runs the command that comes after --. The equivalent of running go test -c ./... && ./test.test. The -c option tell Go to compile into a binary instead of running the test. We need to do this so that the child process would not stay alive after killing the parent process. Here's a more complex use case:

./xnotify -i . -e "(vendor|\.git)$" --batch 50 -- go test -c project.com/package/name -- ./test.test -test.failfast -test.run TestThisFunction

Some explanation on the code:

-e "(vendor|\.git)$" excludes "vendor" and ".git" directory.

--batch 50 will wait for 50ms before executing so that saving multiple files at once wouldn't restart too many times.

This time we pass a package name instead of the path with project.com/package/name.

-test.failfast will stop the test if any tests fails.

-test.run TestThisFunction will only run the test function called "TestThisFunction".

Keywords: go, automatic, cli, xnotify, test, build, server