Live code reloading for Golang web projects in 19 lines

Oleg Lebedev
Dec 9, 2014 · 2 min read

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/
GO_FILES = $(wildcard *.go)
APP = ./app
serve: restart
@fswatch -o . | xargs -n1 -I{} make restart || make kill

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

@echo "actually do nothing"
@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! =)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store