Skip to content

Commit

Permalink
adding value or default context helper
Browse files Browse the repository at this point in the history
  • Loading branch information
Mzack9999 committed Jul 21, 2023
1 parent 5efadaf commit 04c5c27
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
15 changes: 14 additions & 1 deletion context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ import (

var ErrIncorrectNumberOfItems = errors.New("number of items is not even")

var DefaultContext = context.TODO()

type ContextArg string

// WithValues combines multiple key-value into an existing context
func WithValues(ctx context.Context, keyValue ...string) (context.Context, error) {
func WithValues(ctx context.Context, keyValue ...ContextArg) (context.Context, error) {
if len(keyValue)%2 != 0 {
return ctx, ErrIncorrectNumberOfItems
}
Expand All @@ -18,3 +22,12 @@ func WithValues(ctx context.Context, keyValue ...string) (context.Context, error
}
return ctx, nil
}

// ValueOrDefault returns default context if given is nil (using interface to avoid static check reporting)
func ValueOrDefault(value interface{}) context.Context {
if ctx, ok := value.(context.Context); ok && ctx != nil {
return ctx
}

return DefaultContext
}
8 changes: 4 additions & 4 deletions context/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,27 @@ import (
func TestWithValues(t *testing.T) {
type testCase struct {
name string
keyValue []string
keyValue []ContextArg
expectedError error
expectedValue map[string]string
}

var testCases = []testCase{
{
name: "even number of key-value pairs",
keyValue: []string{"key1", "value1", "key2", "value2"},
keyValue: []ContextArg{"key1", "value1", "key2", "value2"},
expectedError: nil,
expectedValue: map[string]string{"key1": "value1", "key2": "value2"},
},
{
name: "odd number of key-value pairs",
keyValue: []string{"key1", "value1", "key2"},
keyValue: []ContextArg{"key1", "value1", "key2"},
expectedError: ErrIncorrectNumberOfItems,
expectedValue: map[string]string{},
},
{
name: "overwriting values",
keyValue: []string{"key1", "value1", "key1", "newValue"},
keyValue: []ContextArg{"key1", "value1", "key1", "newValue"},
expectedError: nil,
expectedValue: map[string]string{"key1": "newValue"},
},
Expand Down

0 comments on commit 04c5c27

Please sign in to comment.