forked from projectdiscovery/utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
33 lines (25 loc) · 813 Bytes
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package contextutil
import (
"context"
"errors"
)
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 ...ContextArg) (context.Context, error) {
if len(keyValue)%2 != 0 {
return ctx, ErrIncorrectNumberOfItems
}
for i := 0; i < len(keyValue)-1; i++ {
ctx = context.WithValue(ctx, keyValue[i], keyValue[i+1]) //nolint
}
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
}