Browser Hot Reload with Golang, Templ, & HTMX

305 views Asked by At

How do I get the browser to auto refresh when ever I save new changes in my go or templates? I got the server to refresh with wgo but the client side (browser) does not refresh which makes it a hassle to develop.

Since I am using HTMX on the client side, I believed I could use that to force a refresh, but it did not seem to feasible without a super hacky solution

3

There are 3 answers

0
MaximilianFullStack On

After doing some research, I found the browser-sync npm package, which can proxy the exposed port and can perform a refresh when code is changed.

To perform the refresh you will have to look for changes on Go and Templ files and ignore changes on '*_templ.go' files (which can cause multiple reloads when Templ generates them). This will also have to take place after your server refresh, which I'm using the WGO package for.

Here is an example bash script implementation to perform all necessary refreshing:

# /bin/bash

wgo -file=.go -file=.templ -xfile=_templ.go templ generate :: go run main.go & \
yarn browser-sync start \
  --files './**/*.go, ./**/*.templ' \
  --ignore '*_templ.go' \
  --port 3001 \
  --proxy 'localhost:3000' \
  --middleware 'function(req, res, next) { \
    res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); \
    return next(); \
  }'

Example implementation repo

0
tmack8080 On

This might help: HOT Reloading The Browser With Templ, Tailwind, And Golang https://www.youtube.com/watch?v=6Pj-Vlhp31Y

0
vbd On

Try https://github.com/cosmtrek/air it provides live reload for Go apps.