-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathid.go
81 lines (60 loc) · 1.33 KB
/
id.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
79
80
81
package jrpc
import (
"context"
"fmt"
"github.com/valyala/fastjson"
)
const (
NullRequestID = "null"
)
type idKey struct{}
func setRequestID(ctx context.Context, id *requestID) context.Context {
return context.WithValue(ctx, idKey{}, id)
}
func RequestID(ctx context.Context) string {
id, _ := ctx.Value(idKey{}).(*requestID)
if id == nil {
return NullRequestID
}
return id.String()
}
type requestID struct {
notNull bool
renderNull bool
stringID *string
intID *int
floatID *float64
}
func (i *requestID) String() string {
if !i.notNull {
return NullRequestID
}
if i.stringID != nil {
return fmt.Sprintf(`"%s"`, *i.stringID)
}
if i.floatID != nil {
return fmt.Sprintf(`%v`, *i.floatID)
}
return fmt.Sprintf(`%v`, *i.intID)
}
func getRequestID(v *fastjson.Value) *requestID {
if !v.Exists("id") {
return &requestID{}
}
idValue := v.Get("id")
intID, err := idValue.Int()
if err != nil {
floatID, err := idValue.Float64()
if err != nil {
bytesID, err := idValue.StringBytes()
if err != nil {
nullReqID := NullRequestID
return &requestID{stringID: &nullReqID, notNull: true}
}
stringID := string(bytesID)
return &requestID{stringID: &stringID, notNull: true}
}
return &requestID{floatID: &floatID, notNull: true}
}
return &requestID{intID: &intID, notNull: true}
}