WithHotReload sets files to watch for file changes to trigger a hot reload update.
(topic string, hub *mercure.Hub, patterns []string)
| 13 | |
| 14 | // WithHotReload sets files to watch for file changes to trigger a hot reload update. |
| 15 | func WithHotReload(topic string, hub *mercure.Hub, patterns []string) Option { |
| 16 | return func(o *opt) error { |
| 17 | o.hotReload = append(o.hotReload, &watcher.PatternGroup{ |
| 18 | Patterns: patterns, |
| 19 | Callback: func(events []*watcherGo.Event) { |
| 20 | // Wait for workers to restart before sending the update |
| 21 | go func() { |
| 22 | data, err := json.Marshal(events) |
| 23 | if err != nil { |
| 24 | if globalLogger.Enabled(globalCtx, slog.LevelError) { |
| 25 | globalLogger.LogAttrs(globalCtx, slog.LevelError, "error marshaling watcher events", slog.Any("error", err)) |
| 26 | } |
| 27 | |
| 28 | return |
| 29 | } |
| 30 | |
| 31 | if err := hub.Publish(globalCtx, &mercure.Update{ |
| 32 | Topics: []string{topic}, |
| 33 | Event: mercure.Event{Data: string(data)}, |
| 34 | Debug: globalLogger.Enabled(globalCtx, slog.LevelDebug), |
| 35 | }); err != nil && globalLogger.Enabled(globalCtx, slog.LevelError) { |
| 36 | globalLogger.LogAttrs(globalCtx, slog.LevelError, "error publishing hot reloading Mercure update", slog.Any("error", err)) |
| 37 | } |
| 38 | }() |
| 39 | }, |
| 40 | }) |
| 41 | |
| 42 | return nil |
| 43 | } |
| 44 | } |