Autoreload go code on code change
For developers, the ability to autoreload code upon any changes is nothing short of a game-changer. It not only streamlines the development process but also fosters an environment of continuous improvement and experimentation.
There are so many packages for languages such as JavaScript for such a behaviour, but I struggled to easily find a simple-to-use go version with an example.
And that’s where this post comes in, as a simple to-the-point example extracted from what I learnt while reading https://dev.to/jacobsngoodwin/full-stack-memory-app-01-setup-go-server-with-reload-in-docker-62n
We will be making use of https://github.com/cespare/reflex, which is a go package and small tool to watch a directory and rerun a command when certain files change.
I’m using this setup for an application that I am running in a docker-compose file.
The docker-compose entry looks something like this:
api:
restart: always
build:
dockerfile: ./go-reload.Dockerfile
ports:
- 8080:80
command: reflex -r "\.go$$" -s -- sh -c "go run ./cmd/api/main.go"
working_dir: /go/src/app
volumes:
- ./:/go/src/app
Code language: JavaScript (javascript)
And the go-reload.Dockerfile
file looks something like this:
FROM golang:1.20
WORKDIR /go/src/app
ENV GO111MODULE=on
RUN go install github.com/cespare/reflex@latest
And Tada, you have an easy-to-install and use auto-reloading system for your go code.