Live code reloading for Golang web projects in 19 lines

In this article I would like to show how you can organize your golang web project with live code reloading. It scheme can be easily extended and will allowed to write couple of line in bash to get what you want.

Why need something new?
There are at least two projects that have similar possibilities, they are this one and this one. They both are Golang oriented, work only with *.go files and I could not find hooks for pre/post compiling commands run. Also they offer to write code in a strictly defined way. That’s why those utilities were not good for me.
So, why use the code snippet I describe? Because this approach is clear and simple, it follows unix philosophy, and it can also be extended and/or configured.

As we know, the code is more expressive then words. Let’s create Makefile in the project’s directory and fill it this way:

PID      = /tmp/awesome-golang-project.pid
GO_FILES = $(wildcard *.go)
APP = ./app
serve: restart
@fswatch -o . | xargs -n1 -I{} make restart || make kill

kill:
@kill `cat $(PID)` || true

before:
@echo "actually do nothing"
$(APP): $(GO_FILES)
@go build $? -o $@
restart: kill before $(APP)
@app & echo $$! > $(PID)

.PHONY: serve restart kill before # let's go to reserve rules names

The code speaks for itself. I think there is no need to comment or describe in more details. Let’s run our server:

$ brew install fswatch # if you don't have
$ make serve

Every time then you change a file content, command `go run` will be restarted for all *.go files in current directory. So, we are done. And previously running processes, if any, will be killed.

Basically, this approach can also be used with other programming languages. If you have questions or comments, please feel free. That’s all! =)

Like what you read? Give Oleg Lebedev a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.