Skip to content

Commit

Permalink
Make default value of Text type usable (#25)
Browse files Browse the repository at this point in the history
This makes a good use case where consumers write tests and just
want some default value instead of explicitly using NewText().
  • Loading branch information
rsjethani authored Oct 15, 2022
1 parent a8f7480 commit b1b9224
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
6 changes: 6 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import (
"github.com/rsjethani/secret/v2"
)

func ExampleText() {
s := secret.Text{}
fmt.Println(s, s.Value())
//Output: *****
}

func ExampleNewText() {
s := secret.NewText("$ecre!")
fmt.Println(s, s.Value())
Expand Down
11 changes: 9 additions & 2 deletions secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ import (
// DefaultRedact is used by default if no other redact hint is given.
const DefaultRedact string = "*****"

// Text provides a way safely to store your secret value and a corresponding redact hint. By
// default this redact hint is returned for operations like printing and serializing.
// Text provides a way to safely store your secret value and a corresponding redact hint. This
// redact hint what is used in operations like printing and serializing. The default
// value of Text is usable.
type Text struct {
// v is the actual secret values.
v *string
Expand Down Expand Up @@ -43,11 +44,17 @@ func NewText(s string, options ...func(*Text)) Text {
// String implements the fmt.Stringer interface and returns only the redact hint. This prevents the
// secret value from being printed to std*, logs etc.
func (s Text) String() string {
if s.r == nil {
return DefaultRedact
}
return *s.r
}

// Value gives you access to the actual secret value stored inside Text.
func (s Text) Value() string {
if s.v == nil {
return ""
}
return *s.v
}

Expand Down
2 changes: 1 addition & 1 deletion secret_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"testing"
)

func TestText_UnmarshalJSON_allocates_new_data_rather_than_overwiting_existing(t *testing.T) {
func TestTextUnmarshalJSON_allocates_new_data_rather_than_overwriting_existing(t *testing.T) {
s1 := NewText("hello")

oldRedact := s1.r
Expand Down

0 comments on commit b1b9224

Please sign in to comment.