-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
87 lines (72 loc) · 1.8 KB
/
api.go
File metadata and controls
87 lines (72 loc) · 1.8 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package mycontrol
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
const (
BaseURLV1 = "https://mycontrol.aero/api/1.0"
)
type Client interface {
GetToken() (string, error)
GetFlight(id string) (*Flight, error)
GetFlights(options *FlightsListOptions) (*FlightsList, error)
AddFlight(flight *Flight) (*Flight, error)
}
type client struct {
baseURL string
apiKey string
token string
HTTPClient *http.Client
}
func NewClient(apiKey string) Client {
return &client{
baseURL: BaseURLV1,
apiKey: apiKey,
token: "",
HTTPClient: &http.Client{
Timeout: time.Minute,
},
}
}
type fieldError struct {
Field string `json:"field"`
Message string `json:"message"`
Code string `json:"code"`
}
type errorResponse struct {
Message string `json:"message"`
Code string `json:"code"`
Errors []fieldError `json:"errors"`
}
// Content-type and body should be already added to req
func (c *client) sendRequest(req *http.Request, v interface{}) error {
token := c.token
if token == "" {
token = c.apiKey
}
req.Header.Set("Accept", "application/json; charset=utf-8")
basicToken := base64.StdEncoding.EncodeToString([]byte(token + ":"))
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", basicToken))
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// Try to unmarshall into errorResponse
if (res.StatusCode != http.StatusOK) && (res.StatusCode != http.StatusCreated) {
var errRes errorResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return errors.New(errRes.Message)
}
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
// Unmarshall and populate v
if err = json.NewDecoder(res.Body).Decode(&v); err != nil {
return err
}
return nil
}