Skip to content

Commit

Permalink
Split Watch and OnChange for watching configuration changes (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
ktong authored Nov 13, 2023
1 parent 0b6c053 commit 38d5dd5
Show file tree
Hide file tree
Showing 13 changed files with 241 additions and 188 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
### Changed

- Split file and fs provider (#49).
- Split Watch and OnChange for watching configuration changes (#52).

### Removed

Expand Down
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ Application also can watch the changes of configuration like:
func main() {
// ... setup global Config ...
konf.Watch(func(){
// Read configuration and reconfig application.
})
go func() {
if err := konf.Watch(ctx); err != nil {
// Handle error here.
}
}
// ... other setup code ...
}
Expand All @@ -65,12 +67,18 @@ configuration source(s). They read configuration in terms of functions in packag

```
func (app *appObject) Run() {
// Read the server configuration.
type serverConfig struct {
Host string
Port int
}
cfg := konf.Get[serverConfig]("server")
// Register callbacks while server configuration changes.
konf.OnChange(func() {
// Reconfig the application object.
}, "server")
// ... use cfg in app code ...
}
```
Expand Down
24 changes: 9 additions & 15 deletions benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ package konf_test

import (
"context"
"sync"
"sync/atomic"
"testing"

"github.com/ktong/konf"
Expand All @@ -14,7 +14,7 @@ import (

func BenchmarkNew(b *testing.B) {
var (
config *konf.Config
config konf.Config
err error
)
for i := 0; i < b.N; i++ {
Expand Down Expand Up @@ -48,27 +48,21 @@ func BenchmarkWatch(b *testing.B) {
assert.NoError(b, err)
konf.SetGlobal(config)

cfg := konf.Get[string]("config")
assert.Equal(b, "string", cfg)
var waitGroup sync.WaitGroup
waitGroup.Add(b.N)
assert.Equal(b, "string", konf.Get[string]("config"))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
err := konf.Watch(ctx, func() {
defer waitGroup.Done()

cfg = konf.Get[string]("config")
})
assert.NoError(b, err)
assert.NoError(b, konf.Watch(ctx))
}()
b.ResetTimer()

var cfg atomic.Value
konf.OnChange(func() {
cfg.Store(konf.Get[string]("config"))
})
for i := 0; i < b.N; i++ {
watcher.change(map[string]any{"config": "changed"})
}
waitGroup.Wait()
b.StopTimer()

assert.Equal(b, "changed", cfg)
assert.Equal(b, "changed", cfg.Load())
}
Loading

0 comments on commit 38d5dd5

Please sign in to comment.