Skip to content

Commit

Permalink
client: return empty secrets from nil Secret and zero Watcher values (#…
Browse files Browse the repository at this point in the history
…114)

As a convenience for the caller, rather than having to check both for nil and
for an empty value, make the Get and GetString methods return appropriate empty
values (nil for []byte, "" for string) on a nil/zero receiver.
  • Loading branch information
creachadair authored Jul 29, 2024
1 parent 0f9da31 commit 5eb656b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
19 changes: 15 additions & 4 deletions client/setec/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -475,12 +475,22 @@ func (s *Store) LookupWatcher(ctx context.Context, name string) (Watcher, error)
type Secret func() []byte

// Get returns the current active value of the secret. It is a legibility
// alias for calling the function.
func (s Secret) Get() []byte { return s() }
// alias for calling the function. If s == nil, Get returns nil.
func (s Secret) Get() []byte {
if s == nil {
return nil
}
return s()
}

// GetString returns a copy of the current active value of the secret as a
// string.
func (s Secret) GetString() string { return string(s()) }
// string. If s == nil, GetString returns "".
func (s Secret) GetString() string {
if s == nil {
return ""
}
return string(s())
}

// StaticSecret returns a Secret that vends a static string value.
// This is useful as a placeholder for development, migration, and testing.
Expand Down Expand Up @@ -765,6 +775,7 @@ type Watcher struct {
}

// Get returns the current active value of the secret.
// A zero-valued Watcher returns nil.
func (w Watcher) Get() []byte { return w.secret.Get() }

// Ready returns a channel that delivers a value when the current active
Expand Down
15 changes: 15 additions & 0 deletions client/setec/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,21 @@ func TestNewFileCache(t *testing.T) {
})
}

func TestNilSecret(t *testing.T) {
var s setec.Secret
var w setec.Watcher

if got := s.Get(); got != nil {
t.Errorf("(nil).Get: got %v, want nil", got)
}
if got := s.GetString(); got != "" {
t.Errorf(`(nil).GetString: got %q, want ""`, got)
}
if got := w.Get(); got != nil {
t.Errorf("(zero).Get: got %v, want nil", got)
}
}

type badCache struct{}

func (badCache) Write([]byte) error { return errors.New("write failed") }
Expand Down

0 comments on commit 5eb656b

Please sign in to comment.