-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
68 lines (50 loc) · 1.51 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
59
60
61
62
63
64
65
66
67
68
package golist
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strconv"
)
// All unusual responses from the botblock api!
var UnusualResponses []int = []int{400, 401, 404, 429, 500}
func isUnusualResponse(code int) bool {
for _, i := range UnusualResponses {
if i == code {
return true
}
}
return false
}
// Simply fetches from the botblock api in an easy way!
func Fetch(method string, url string, structure interface{}, body map[string]interface{}) error {
client := &http.Client{}
marshalledBody, _ := json.Marshal(body)
jsonBody := bytes.NewBuffer(marshalledBody)
req, err := http.NewRequest(method, "https://botblock.org/api"+url, jsonBody)
_, hasBody := body["bot_id"]
if hasBody {
req.Header.Add("Content-Type", "application/json")
}
if err != nil {
return errors.New("UnexpectedError: Failed making a request")
}
res, err := client.Do(req)
if err != nil {
return errors.New("UnexpectedError: Failed making a request")
}
data, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
return errors.New("UnexpectedError: Failed reading request data")
}
marshallErr := json.Unmarshal(data, structure)
if marshallErr != nil {
return errors.New("UnexpectedError: Failed while marshalling json: " + marshallErr.Error())
}
unusual := isUnusualResponse(res.StatusCode)
if unusual {
return errors.New("BotblockApiError: Botblock api sent an unusual api response as " + string(data) + " with status code as " + strconv.Itoa(res.StatusCode) + "!")
}
return nil
}