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. This approach can be easily adapted for a variety of scenarios regarding an OS process restarts with connection to files’ changes, independently to a language your project has been written in.
Is this even an issue?
There are plenty of projects for any kind of similar scenarios you can think of regarding code reloading, most notable projects in the Golang ecosystem are this one and this one. They are pretty much *.go
files specific and I could not find any hooks to execute own-written commands, for example, to compile files written for thepost-css
processor. Also, these projects forced me to write code in a strictly defined way. However, I would prefer to have more flexibility. That’s why those projects were not quite good to me.
Also, I am pretty much a fan of a clean and concise approach, so I was wondering if this could be done once in a generic way and then and being reused with the same efficiency for any kind of live code reloading purposes.
Sold! Shut up and take my money!
Okay, let’s create a file named Makefile
in the project’s directory and fill it in this way:
PID = /tmp/awesome-golang-project.pid
GO_FILES = $(wildcard *.go)
APP = ./appserve: restart
@fswatch -o . | xargs -n1 -I{} make restart || make kill
kill:
@kill `cat $(PID)` || true
before:
@echo "TODO: inject you hooks here"$(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
And then let’s run our server:
$ brew install fswatch # if you don't have
$ make serve
The./app
artifact will be rebuilt and restarted for all *.go
files changes in the current directory, and previously running processes, if any, will be killed.
The approach can be used with other programming languages. If you have questions or comments, please feel free to post them below. That’s it for now!