-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.go
96 lines (93 loc) · 2.16 KB
/
array.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package tpl
import (
"context"
"encoding/json"
"fmt"
"log"
"net/url"
"strconv"
"github.com/KarpelesLab/pjson"
)
func ResolveValueIndex(ctx context.Context, v any, s string) (any, error) {
switch o := v.(type) {
case ArrayAccessGet:
return o.OffsetGet(ctx, s)
case ArrayAccessGetAny:
return o.OffsetGet(ctx, s)
case map[string]any:
return o[s], nil
case map[string]Value:
return o[s], nil
case map[string]json.RawMessage:
return o[s], nil
case map[string]pjson.RawMessage:
return o[s], nil
case url.Values:
return o[s], nil
case Values:
n, err := strconv.ParseInt(s, 0, 64)
if err != nil {
log.Printf("[tpl] failed to access array element #%s", s)
return nil, nil
}
if n < 0 || int(n) >= len(o) {
return nil, nil
}
return o[n], nil
case []any:
n, err := strconv.ParseInt(s, 0, 64)
if err != nil {
log.Printf("[tpl] failed to access array element #%s", s)
return nil, nil
}
if n < 0 || int(n) >= len(o) {
return nil, nil
}
return o[n], nil
case []string:
n, err := strconv.ParseInt(s, 0, 64)
if err != nil {
log.Printf("[tpl] failed to access array element #%s", s)
return nil, nil
}
if n < 0 || int(n) >= len(o) {
return nil, nil
}
return o[n], nil
case json.RawMessage:
// parse at json object
var sub interface{}
err := json.Unmarshal(o, &sub)
if err != nil {
return nil, fmt.Errorf("failed to parse json: %s", err)
}
return ResolveValueIndex(ctx, sub, s)
case pjson.RawMessage:
// parse at json object
var sub interface{}
err := json.Unmarshal(o, &sub)
if err != nil {
return nil, fmt.Errorf("failed to parse json: %s", err)
}
return ResolveValueIndex(ctx, sub, s)
case interface{ RawJSONBytes() []byte }:
// parse at json object
var sub any
err := json.Unmarshal(o.RawJSONBytes(), &sub)
if err != nil {
return nil, fmt.Errorf("failed to parse json: %s", err)
}
return ResolveValueIndex(ctx, sub, s)
case ValueReader:
val, err := o.ReadValue(ctx)
if err != nil {
return nil, err
}
return ResolveValueIndex(ctx, val, s)
case nil:
return nil, nil
default:
//log.Printf("unhandled type: %T", val)
return nil, fmt.Errorf("unhandled type: %T", v)
}
}