-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_wx.go
138 lines (113 loc) · 2.37 KB
/
check_wx.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package checkwx
import (
"encoding/json"
"fmt"
"github.com/moul/http2curl"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
)
type CheckWx struct {
client *http.Client
apiKey string
Debug bool
QueryParams map[string]string
Headers map[string]string
BaseURL string
Station *StationService
Metar *MetarService
Taf *TafService
}
func NewCheckWx(apiKey string) *CheckWx {
cw := &CheckWx{
client: http.DefaultClient,
apiKey: apiKey,
Debug: false,
Headers: map[string]string{
"Content-Type": "application/json",
"X-API-Key": apiKey,
},
BaseURL: "https://api.checkwx.com",
}
cw.Station = &StationService{cw: cw}
cw.Metar = &MetarService{cw: cw}
cw.Taf = &TafService{cw: cw}
return cw
}
func (c *CheckWx) newRequest(method, path string, query url.Values, body io.Reader) (*http.Request, error) {
u, err := url.Parse(c.BaseURL)
if err != nil {
return nil, err
}
for key, value := range c.QueryParams {
query.Set(key, value)
}
u.Path = path
u.RawQuery = query.Encode()
req, err := http.NewRequest(method, u.String(), body)
if err != nil {
return nil, err
}
for key, value := range c.Headers {
req.Header.Set(key, value)
}
return req, nil
}
func (c *CheckWx) do(req *http.Request, v interface{}) error {
if c.Debug == true {
command, _ := http2curl.GetCurlCommand(req)
fmt.Println(command)
}
res, err := c.client.Do(req)
if err != nil {
return err
}
if res.StatusCode >= 200 && res.StatusCode < 400 {
if v != nil {
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&v)
if err != nil {
return err
}
}
return nil
}
apiError := c.handleError(req, res)
if apiError != nil {
return apiError
}
return c.do(req, v)
}
func (c *CheckWx) handleError(req *http.Request, res *http.Response) error {
if c.Debug == true {
dump, err := httputil.DumpResponse(res, true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%q", dump)
}
var e ErrorResponse
defer res.Body.Close()
err := json.NewDecoder(res.Body).Decode(&e)
if err != nil {
return err
}
apiError := ApiError{
req: req,
res: res,
err: &e,
}
switch status := apiError.res.StatusCode; status {
case 401:
return InvalidHeaderApiKeyError{apiError}
case 429:
return ApiRateLimitError{apiError}
case 500:
return ServerError{apiError}
default:
return UnknownError{apiError}
}
return e
}