mirror of
https://github.com/go-kratos/kratos.git
synced 2025-03-17 21:07:54 +02:00
chore(config/env): polish watcher (#1341)
* chore(config/env): polish watcher
This commit is contained in:
parent
80378ca10d
commit
3026f9490e
7
config/env/watcher.go
vendored
7
config/env/watcher.go
vendored
@ -7,8 +7,6 @@ import (
|
||||
)
|
||||
|
||||
type watcher struct {
|
||||
exit chan struct{}
|
||||
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
@ -17,7 +15,7 @@ var _ config.Watcher = (*watcher)(nil)
|
||||
|
||||
func NewWatcher() (config.Watcher, error) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &watcher{exit: make(chan struct{}), ctx: ctx, cancel: cancel}, nil
|
||||
return &watcher{ctx: ctx, cancel: cancel}, nil
|
||||
}
|
||||
|
||||
// Next will be blocked until the Stop method is called
|
||||
@ -25,13 +23,10 @@ func (w *watcher) Next() ([]*config.KeyValue, error) {
|
||||
select {
|
||||
case <-w.ctx.Done():
|
||||
return nil, w.ctx.Err()
|
||||
case <-w.exit:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (w *watcher) Stop() error {
|
||||
close(w.exit)
|
||||
w.cancel()
|
||||
return nil
|
||||
}
|
||||
|
29
config/env/watcher_test.go
vendored
Normal file
29
config/env/watcher_test.go
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
package env
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func Test_watcher_next(t *testing.T) {
|
||||
t.Run("next after stop should return err", func(t *testing.T) {
|
||||
w, err := NewWatcher()
|
||||
require.NoError(t, err)
|
||||
|
||||
_ = w.Stop()
|
||||
_, err = w.Next()
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_watcher_stop(t *testing.T) {
|
||||
t.Run("stop multiple times should not panic", func(t *testing.T) {
|
||||
w, err := NewWatcher()
|
||||
require.NoError(t, err)
|
||||
|
||||
_ = w.Stop()
|
||||
_ = w.Stop()
|
||||
})
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user