Documentation ¶
Overview ¶
Package reload exposes the middleware Handle(), which can be used to trigger a reload in the browser whenever a file is changed.
Reload doesn't require any external tools and is can be integrated into any project that uses the standard net/http interface.
Typically, integrating this package looks like this:
1. Create a new Reloader and insert the middleware to your handler chain:
// handler can be anything that implements http.Handler, // like chi.Router, echo.Echo or gin.Engine var handler http.Handler = http.DefaultServeMux if isDevelopment { // Call `New()` with a list of directories to recursively watch reloader := reload.New("ui/") // Optionally, define a callback to // invalidate any caches reloader.OnReload = func() { app.parseTemplates() } // Use the Handle() method as a middleware handler = reloader.Handle(handler) } http.ListenAndServe(addr, handler)
2. Run your application, make changes to files in the specified directories, and see the updated page instantly! The package also exposes `ServeWS`, `InjectScript`, `Wait` and `WatchDirectories`, which can be used to embed the script in the templates directly.
See the full example at https://github.com/aarol/reload/blob/main/example/main.go
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func InjectedScript ¶
InjectedScript Returns the javascript that will be injected on each HTML page.
Types ¶
type Reloader ¶
type Reloader struct { // OnReload will be called after a file changes, but before the browser reloads. OnReload func() // Endpoint defines what path the WebSocket connection is formed over. // It is set to "/reload_ws" by default. Endpoint string // When set to true, prevents the middleware from sending a "Cache-Control=no-cache" header on each request. // // Some handlers, like http.FileServer send Last-Modified headers, which prevent the browser from refetching changed files correctly. // // To prevent confusion, caching is disabled by default. // It is also possible to enable this option, and use a middleware like Chi's NoCache (https://github.com/go-chi/chi/blob/master/middleware/nocache.go) AllowCaching bool Log *log.Logger // Used to upgrade connections to Websocket connections Upgrader websocket.Upgrader // contains filtered or unexported fields }
func (*Reloader) Handle ¶
Handle starts the reload middleware, watching the specified directories and injecting the script into HTML responses.
func (*Reloader) ServeWS ¶
func (reload *Reloader) ServeWS(w http.ResponseWriter, r *http.Request)
ServeWS is the default websocket endpoint. Implementing your own is easy enough if you don't want to use 'gorilla/websocket'
func (*Reloader) WatchDirectories ¶
func (reload *Reloader) WatchDirectories()
WatchDirectories listens for changes in directories and broadcasts on write.