-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstash.go
78 lines (62 loc) · 2.12 KB
/
stash.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package rpc
import (
"context"
"encoding/json"
"errors"
"fmt"
)
type stashKey int
const stashKeyValue stashKey = 0
var ErrNoStash = errors.New("stash not found in context")
var ErrUnexpectedStashType = errors.New("unexpected stash type")
var ErrNilContext = errors.New("context is nil")
// SetStash sets the stash value in the context.
// It marshals the stash value to JSON and stores it in the context using a specific key.
// If the context is nil, it returns an error.
// If there is an error while marshalling the stash value, it returns an error with the specific error message.
// Otherwise, it returns the updated context with the stash value set.
func SetStash(ctx context.Context, stash any) (context.Context, error) {
if ctx == nil {
return nil, ErrNilContext
}
stashStr, err := json.Marshal(stash)
if err != nil {
return nil, fmt.Errorf("error marshalling stash: %w", err)
}
ctx = context.WithValue(ctx, stashKeyValue, string(stashStr))
return ctx, nil
}
// ParseStash parses the stash value from the context and unmarshals it into the provided value.
// It returns an error if the stash value is not found in the context or if it has an unexpected type.
func ParseStash(ctx context.Context, v any) error {
stash := ctx.Value(stashKeyValue)
if stash == nil {
return ErrNoStash
}
stashStr, ok := stash.(string)
if !ok {
return ErrUnexpectedStashType
}
if err := json.Unmarshal([]byte(stashStr), v); err != nil {
return fmt.Errorf("error unmarshalling stash: %w", err)
}
return nil
}
// getStash retrieves the serialized stash from the provided context.
// It returns the serialized stash as a byte slice and an error, if any.
func getStash(ctx context.Context) string {
stash := ctx.Value(stashKeyValue)
if stash == nil {
return ""
}
serialized, ok := stash.(string)
if !ok {
panic(ErrUnexpectedStashType)
}
return serialized
}
// putStash puts the given stash into the context and returns the updated context.
// If the provided context is nil, it panics with ErrNilContext.
func putStash(ctx context.Context, stash string) context.Context {
return context.WithValue(ctx, stashKeyValue, stash)
}