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 ¶
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
// Deprecated: see DisableCaching instead.
AllowCaching bool
// DisableCaching is set to true by default. Writes a "Cache-Control=no-cache" header on each response.
//
// Some http.Handlers, like http.FileServer, automatically write a Last-Modified header.
// Browser will usually cache the resource if no changes occur after multiple requests.
DisableCaching bool
// Deprecated: Use ErrorLog instead.
Log *log.Logger
// Enable this logger to print debug information (when the reloads happen, etc)
DebugLog *log.Logger
ErrorLog *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.