-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffset.go
68 lines (64 loc) · 1.46 KB
/
offset.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
package typutil
import (
"context"
"fmt"
"net/url"
"reflect"
)
type offsetGetter interface {
OffsetGet(context.Context, string) (any, error)
}
type valueReader interface {
ReadValue(ctx context.Context) (any, error)
}
// OffsetGet returns v[offset] dealing with various case of figure. ctx will be passed to some methods handling it
func OffsetGet(ctx context.Context, v any, offset string) (any, error) {
switch a := v.(type) {
case offsetGetter:
return a.OffsetGet(ctx, offset)
case map[string]any:
return a[offset], nil
case map[string]string:
return a[offset], nil
case url.Values:
res := a[offset]
if len(res) == 0 {
return nil, nil
} else {
return res[0], nil
}
case []any:
// convert offset to int, ensure it is in range
n, ok := AsUint(offset)
if !ok {
return nil, fmt.Errorf("%w: %T", ErrBadOffset, offset)
}
if n < 0 || n >= uint64(len(a)) {
// silent error
return nil, nil
}
return a[n], nil
case valueReader: // keep this last
nv, err := a.ReadValue(ctx)
if err != nil {
return nil, err
}
return OffsetGet(ctx, nv, offset)
default:
vr := reflect.ValueOf(v)
switch vr.Kind() {
case reflect.Map:
switch vr.Type().Key().Kind() {
case reflect.String:
// this we can handle
v := vr.MapIndex(reflect.ValueOf(offset))
if v.IsZero() {
return nil, nil
} else {
return v.Interface(), nil
}
}
}
return nil, fmt.Errorf("unsupported type %T for offset fetching", v)
}
}