-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapaccess.go
58 lines (55 loc) · 1.35 KB
/
mapaccess.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
package mapaccess
import (
"fmt"
"reflect"
"strconv"
)
// Get returns the corresponding key from the map
func Get(data interface{}, key string) (interface{}, error) {
var err error
state := data
parser := parse(key)
token := parser.nextItem()
for token.typ != tokenEnd && token.typ != tokenError {
if state, err = get(state, token); err != nil {
return nil, err
}
token = parser.nextItem()
}
if token.typ == tokenError {
return nil, fmt.Errorf(token.val)
}
return state, nil
}
func get(data interface{}, key token) (interface{}, error) {
switch state := data.(type) {
case map[string]interface{}:
switch key.typ {
case tokenIdentifier:
if res, ok := state[key.val]; ok {
return res, nil
}
return nil, fmt.Errorf("key not found")
default:
return nil, fmt.Errorf("key not found")
}
case []interface{}:
switch key.typ {
case tokenArrayIndex:
index, err := strconv.Atoi(key.val)
if err != nil {
return nil, fmt.Errorf("expected array index, but got %s", key.val)
}
if index < 0 || index >= len(state) {
return nil, fmt.Errorf("index out of bounds %s", key.val)
}
return state[index], nil
default:
return nil, fmt.Errorf("key not found")
}
case nil:
return nil, fmt.Errorf("key <%s> not found", key.val)
default:
return nil, fmt.Errorf("can't deal with this type %s", reflect.TypeOf(data))
}
}