Repository navigation
Expand file tree
/
Copy pathapi.go
More file actions
66 lines (52 loc) · 1.44 KB
/
Copy pathapi.go
File metadata and controls
66 lines (52 loc) · 1.44 KB
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
package coconut
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
const USER_AGENT = "Coconut/v2 GoBindings/2.0.0"
type API struct {
client Client
}
type P map[string]interface{}
func (p P) String() string {
jsonString, _ := json.Marshal(p)
return string(jsonString)
}
func (a API) Request(m string, p string, data P) (map[string]interface{}, error) {
url := a.client.GetEndpoint() + p
var req *http.Request
var err error
if m == "GET" {
req, err = http.NewRequest("GET", url, nil)
} else if m == "POST" {
req, err = http.NewRequest("POST", url, bytes.NewBuffer([]byte(data.String())))
}
req.SetBasicAuth(a.client.APIKey, "")
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", USER_AGENT)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, Error{Code: "request_error", Message: "Request error", Status: "error"}
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
// errors
if resp.StatusCode > 399 {
if resp.StatusCode == 400 || resp.StatusCode == 401 {
var err = Error{}
json.Unmarshal([]byte(body), &err)
return nil, err
} else {
msg := fmt.Sprintf("Server returned HTTP status code %d", resp.StatusCode)
return nil, Error{Code: "server_error", Message: msg, Status: "error"}
}
}
var result map[string]interface{}
json.Unmarshal([]byte(body), &result)
return result, nil
}