GO live reloading
One of the nice things about javsctipt development, is hot module replacement, when your working on a web application and when you make a code change your local running instance is automagically updated with your changes, making the development feedback loop much quicker.
HMR can replace a module in your running instance without having to restart the process, I assume because javascript is a JIT language this is easier than a compiled language like GO.
Air
But there exists a tool called Air that will give us similiar results, it is not HMR like in js land but Air can listen for changes in your files and rebuild and run your GO application.
You can get started by initiliazing:
air init
This creates a toml file which you can configure to suit your application.
Here is the build config in my toml for a web application
[build]
args_bin = ["serve"]
bin = "./tmp/main"
cmd = "make server"
delay = 1000
exclude_dir = ["assets", "tmp"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html", "templ"]
include_file = ["assets/css/styles.css"]
kill_delay = "0s"
log = "build-errors.log"
poll = false
poll_interval = 0
post_cmd = []
pre_cmd = []
rerun = false
rerun_delay = 500
send_interrupt = false
stop_on_error = false
Air works by watching folders and files you specify
Notice include_ext
I have go, html and templ files and I have explicity included my stylesheet which uses tailwindcss
I have also excluded the assets and tmp folder as those dont affect the application build.
When Air detects a file has changed it will kill the process and call the cmd
make server
which calls my make command to build the go application
go build -o ./tmp/main ./cmd/main.go
The build creates the executable in the tmp folder
Air uses the bin
field and passes the args_bin to run the application, so in my case it will look like this
./tmp/main serve
So now we have can develop our application and run locally and air will detect changes and rerun our application locally, so we now get a nice quick feedback loop without having to constantly rebuild our go project.
Makefile I have an accompanying make file that will run our application using air, regenerate my templ files and rebuild my css stylesheet with the tailwind cli.
live:
make -j3 templ air css
This asks make to run these three commands using 3 processes.
Here are those commands:
templ:
templ generate --watch --proxy="http://localhost:8080" --open-browser=false -v
air:
air -c .air.toml
css:
npx tailwindcss -i ./assets/css/base.css -o ./assets/css/styles.css --watch