-
Notifications
You must be signed in to change notification settings - Fork 18
/
request.go
69 lines (64 loc) · 1.3 KB
/
request.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
package main
import (
"net/http"
"encoding/json"
"io/ioutil"
"errors"
"strconv"
"path/filepath"
"os"
)
func RequestJSON(url string) (map[string]interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New("Unknown server error (" + strconv.Itoa(resp.StatusCode) + ").")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
return nil, err
}
return data, nil
}
func RequestAPI(url string) (map[string]interface{}, error) {
data, err := RequestJSON(url)
if err != nil {
return nil, err
}
if !CheckRequestStatus(data) {
return nil, errors.New("Unknown server error")
}
return data, nil
}
func CheckRequestStatus(data map[string]interface{}) bool {
return data["status"] == "success"
}
func RequestToPath(url, path string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
parent := filepath.Join(path, "..")
err = os.MkdirAll(parent, 0777)
if err != nil {
return err
}
err = ioutil.WriteFile(path, data, 0777)
if err != nil {
return err
}
return nil
}