forked from pingcap/tidb-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
58 lines (50 loc) · 1.37 KB
/
util.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 utils
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/pingcap/errors"
)
// SliceToMap converts slice to map
func SliceToMap(slice []string) map[string]interface{} {
sMap := make(map[string]interface{})
for _, str := range slice {
sMap[str] = struct{}{}
}
return sMap
}
// StringsToInterfaces converts string slice to interface slice
func StringsToInterfaces(strs []string) []interface{} {
is := make([]interface{}, 0, len(strs))
for _, str := range strs {
is = append(is, str)
}
return is
}
// GetJSON fetches a page and parses it as JSON. The parsed result will be
// stored into the `v`. The variable `v` must be a pointer to a type that can be
// unmarshalled from JSON.
//
// Example:
//
// client := &http.Client{}
// var resp struct { IP string }
// if err := util.GetJSON(client, "http://api.ipify.org/?format=json", &resp); err != nil {
// return errors.Trace(err)
// }
// fmt.Println(resp.IP)
func GetJSON(client *http.Client, url string, v interface{}) error {
resp, err := client.Get(url)
if err != nil {
return errors.Trace(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Trace(err)
}
return errors.Errorf("get %s http status code != 200, message %s", url, string(body))
}
return errors.Trace(json.NewDecoder(resp.Body).Decode(v))
}