Watch starts watching for configuration changes and automatically updates the target struct name: the name of the watcher, which is used to identify this watcher This method sets up a watcher that will call Load() when configuration changes are detected
(ctx context.Context, name string)
| 143 | // name: the name of the watcher, which is used to identify this watcher |
| 144 | // This method sets up a watcher that will call Load() when configuration changes are detected |
| 145 | func (l *Loader[T]) Watch(ctx context.Context, name string) error { |
| 146 | if name == "" { |
| 147 | return gerror.New("Watcher name cannot be empty") |
| 148 | } |
| 149 | adapter := l.config.GetAdapter() |
| 150 | if watcherAdapter, ok := adapter.(WatcherAdapter); ok { |
| 151 | watcherAdapter.AddWatcher(name, func(ctx context.Context) { |
| 152 | // Reload configuration when change is detected |
| 153 | if err := l.Load(ctx); err != nil { |
| 154 | // Use the configured error handler if available, otherwise execute default logging |
| 155 | if l.watchErrorFunc != nil { |
| 156 | l.watchErrorFunc(ctx, err) |
| 157 | } else { |
| 158 | // Default logging using intlog (internal logging for development) |
| 159 | intlog.Errorf(ctx, "Configuration load failed in watcher %s: %v", name, err) |
| 160 | } |
| 161 | } |
| 162 | }) |
| 163 | l.watcherName = name |
| 164 | return nil |
| 165 | } |
| 166 | return gerror.New("Watcher adapter not found") |
| 167 | } |
| 168 | |
| 169 | // MustWatch is like Watch but panics if there is an error |
| 170 | func (l *Loader[T]) MustWatch(ctx context.Context, name string) { |
no test coverage detected