-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathutils.go
74 lines (63 loc) · 1.2 KB
/
utils.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
package coze
import (
"context"
"crypto/rand"
"encoding/json"
)
func ptrValue[T any](s *T) T {
if s != nil {
return *s
}
var empty T
return empty
}
func ptr[T any](s T) *T {
return &s
}
func generateRandomString(length int) (string, error) {
bytes := make([]byte, length/2)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return bytesToHex(bytes), nil
}
func bytesToHex(bytes []byte) string {
hex := make([]byte, len(bytes)*2)
for i, b := range bytes {
hex[i*2] = hexChar(b >> 4)
hex[i*2+1] = hexChar(b & 0xF)
}
return string(hex)
}
func hexChar(b byte) byte {
if b < 10 {
return '0' + b
}
return 'a' + (b - 10)
}
func mustToJson(obj any) string {
jsonArray, err := json.Marshal(obj)
if err != nil {
return "{}"
}
return string(jsonArray)
}
type contextKey string
const (
authContextKey = contextKey("auth_context")
authContextValue = "1"
)
func genAuthContext(ctx context.Context) context.Context {
return context.WithValue(ctx, authContextKey, authContextValue)
}
func isAuthContext(ctx context.Context) bool {
v := ctx.Value(authContextKey)
if v == nil {
return false
}
strV, ok := v.(string)
if !ok {
return false
}
return strV == authContextValue
}