-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkeyvalue.go
174 lines (142 loc) · 3.93 KB
/
keyvalue.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package keyvalue
// Service provided by: https://keyvalue.xyz/
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
)
// KeyValue struct
type KeyValue struct {
Token string `json:"token"`
Key string `json:"key"`
Value string `json:"value"`
}
// NewKeyValue gets a new key-value with given key string
func NewKeyValue(key string) (kv *KeyValue, err error) {
// request format: "https://api.keyvalue.xyz/new/some-key"
result, err := postURL(fmt.Sprintf("https://api.keyvalue.xyz/new/%s", url.QueryEscape(key)))
if err == nil {
// result format: "https://api.keyvalue.xyz/0123456/some-key"
splits := strings.Split(result, "/")
cnt := len(splits)
// sanity check 1
if cnt <= 2 {
return nil, fmt.Errorf("Wrong response from server: %s", result)
}
t, k := splits[cnt-2], splits[cnt-1] // token: "0123456", key: "some-key"
// sanity check 2
if k != key {
return nil, fmt.Errorf("Returned key is different from the request: %s - %s", k, key)
}
return &KeyValue{
Token: t,
Key: k,
}, nil
}
return nil, err
}
// NewKeyValueWithToken gets a key-value with stored token and key string
func NewKeyValueWithToken(token, key string) *KeyValue {
return &KeyValue{
Token: token,
Key: key,
}
}
// Set sets a value
func (kv *KeyValue) Set(value string) error {
// request format: "https://api.keyvalue.xyz/0123456/some-key/some-value"
if _, err := postURL(fmt.Sprintf("https://api.keyvalue.xyz/%s/%s/%s", kv.Token, url.QueryEscape(kv.Key), url.QueryEscape(value))); err != nil {
return err
}
return nil
}
// SetAndValidate sets a value (and validate it by comparing with the changed value)
func (kv *KeyValue) SetAndValidate(value string) error {
if err := kv.Set(value); err != nil {
return err
}
if v, err := kv.Get(); err != nil {
return err
} else if v != value {
return fmt.Errorf("Returned value is different from the request: %s - %s", v, value)
}
return nil
}
// SetObject sets an object as a value
func (kv *KeyValue) SetObject(obj interface{}) error {
bytes, err := json.Marshal(obj)
if err == nil {
return kv.Set(string(bytes))
}
return err
}
// SetObjectAndValidate sets an object and validate it by calling the given function
func (kv *KeyValue) SetObjectAndValidate(obj interface{}, equals func(returned string, requested interface{}) bool) error {
var err error
var bytes []byte
bytes, err = json.Marshal(obj)
if err == nil {
err = kv.Set(string(bytes))
if err == nil {
var val string
val, err = kv.Get()
if err == nil {
if equals(val, obj) {
return nil
}
return fmt.Errorf("Validation failed: `%s` differs from `%+v`", val, obj)
}
}
}
return err
}
// Get gets a stored value
func (kv *KeyValue) Get() (string, error) {
// request format: "https://api.keyvalue.xyz/0123456/some-key"
result, err := getURL(fmt.Sprintf("https://api.keyvalue.xyz/%s/%s", kv.Token, url.QueryEscape(kv.Key)))
if err != nil {
return "", err
}
return result, nil
}
func postURL(url string) (string, error) {
return request("POST", url)
}
func getURL(url string) (string, error) {
return request("GET", url)
}
func request(method, url string) (result string, err error) {
var req *http.Request
if req, err = http.NewRequest(method, url, nil); err == nil {
client := &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 300 * time.Second,
}).Dial,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
var resp *http.Response
resp, err = client.Do(req)
if resp != nil {
defer resp.Body.Close()
}
if err == nil {
if resp.StatusCode == 200 {
res, _ := ioutil.ReadAll(resp.Body)
return strings.TrimSuffix(string(res), "\n"), nil
}
return "", fmt.Errorf("Request error: %s", resp.Status)
}
}
return "", err
}