forked from ava-labs/ortelius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
119 lines (100 loc) · 2.48 KB
/
query.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// (c) 2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package params
import (
"net/url"
"strconv"
"strings"
"time"
"github.com/corpetty/avalanchego/ids"
"github.com/corpetty/avalanchego/utils/formatting"
)
func GetQueryInt(q url.Values, key string, defaultVal int) (val int, err error) {
strs := q[key]
if len(strs) >= 1 {
return strconv.Atoi(strs[0])
}
return defaultVal, err
}
func GetQueryBool(q url.Values, key string, defaultVal bool) (val bool, err error) {
strs := q[key]
if len(strs) >= 1 {
return strconv.ParseBool(strs[0])
}
return defaultVal, err
}
func GetQueryString(q url.Values, key string, defaultVal string) string {
strs := q[key]
if len(strs) >= 1 {
return strs[0]
}
return defaultVal
}
func GetQueryTime(q url.Values, key string) (bool, time.Time, error) {
strs, ok := q[key]
if !ok || len(strs) < 1 {
return false, time.Time{}, nil
}
timestamp, err := strconv.Atoi(strs[0])
if err == nil {
return true, time.Unix(int64(timestamp), 0).UTC(), nil
}
t, err := time.Parse(time.RFC3339, strs[0])
if err != nil {
return false, time.Time{}, err
}
return true, t, nil
}
func GetQueryID(q url.Values, key string) (*ids.ID, error) {
idStr := GetQueryString(q, key, "")
if idStr == "" {
return nil, nil
}
id, err := ids.FromString(idStr)
if err != nil {
return nil, err
}
return &id, nil
}
func GetQueryInterval(q url.Values, key string) (time.Duration, error) {
intervalStrs, ok := q[key]
if !ok || len(intervalStrs) < 1 {
return 0, nil
}
interval, ok := IntervalNames[intervalStrs[0]]
if !ok {
var err error
interval, err = time.ParseDuration(intervalStrs[0])
if err != nil {
return 0, err
}
}
return interval, nil
}
func GetQueryAddress(q url.Values, key string) (*ids.ShortID, error) {
addrStr := GetQueryString(q, key, "")
if addrStr == "" {
return nil, nil
}
addr, err := AddressFromString(addrStr)
if err != nil {
return nil, err
}
return &addr, nil
}
var addressPrefixes = []string{"X", "P", "C"}
func AddressFromString(addrStr string) (ids.ShortID, error) {
for _, prefix := range addressPrefixes {
addrStr = strings.TrimPrefix(addrStr, prefix+"-")
addrStr = strings.TrimPrefix(addrStr, strings.ToLower(prefix)+"-")
}
_, addrBytes, err := formatting.ParseBech32(addrStr)
if err != nil {
addrFromShortIDStr, err := ids.ShortFromString(addrStr)
if err == nil {
return addrFromShortIDStr, nil
}
return ids.ShortEmpty, err
}
return ids.ToShortID(addrBytes)
}