-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
149 lines (116 loc) · 3.43 KB
/
connection.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
139
140
141
142
143
144
145
146
147
148
149
package gopensky
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
)
const (
openSkyAPIURL = "https://opensky-network.org:443/api"
clientKey = valueKey("Client")
)
type valueKey string
type apiResponse struct {
*http.Response
Request *http.Request
}
type Connection struct {
auth string
uri *url.URL
client *http.Client
}
func newConnectionError(err error) error {
return connectionError{err: err}
}
func NewConnection(ctx context.Context, username string, password string) (context.Context, error) {
_url, err := url.Parse(openSkyAPIURL)
if err != nil {
perr := fmt.Errorf("invalid url %s: %w", openSkyAPIURL, err)
return nil, newConnectionError(perr)
}
connection := Connection{
uri: _url,
}
if username != "" {
connection.auth = base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
}
dialContext := func(ctx context.Context, _, _ string) (net.Conn, error) { //nolint:revive
return net.Dial("tcp", _url.Host)
}
connection.client = &http.Client{
Transport: &http.Transport{
DialContext: dialContext,
DisableCompression: true,
},
}
return context.WithValue(ctx, clientKey, &connection), nil
}
// getClient from context build by NewConnection().
func getClient(ctx context.Context) (*Connection, error) {
if c, ok := ctx.Value(clientKey).(*Connection); ok {
return c, nil
}
return nil, fmt.Errorf("%w %s", errContextKey, clientKey)
}
func (c *Connection) doGetRequest(ctx context.Context, endpoint string, queryParams url.Values,
) (*apiResponse, error) {
requestURL := fmt.Sprintf("%s/%s", c.uri, endpoint)
if len(queryParams) > 0 {
params := queryParams.Encode()
requestURL = fmt.Sprintf("%s?%s", requestURL, params)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)
if err != nil {
return nil, fmt.Errorf("new request: %w", err)
}
if c.auth != "" {
req.Header.Add("Authorization", "Basic "+c.auth)
}
response, err := c.client.Do(req) //nolint:bodyclose
return &apiResponse{response, req}, err //nolint:wrapcheck
}
func (h *apiResponse) isInformational() bool {
return h.Response.StatusCode/100 == 1
}
func (h *apiResponse) isSuccess() bool {
return h.Response.StatusCode/100 == 2 //nolint:mnd
}
func (h *apiResponse) isRedirection() bool {
return h.Response.StatusCode/100 == 3 //nolint:mnd
}
// process drains the response body, and processes the HTTP status code
// Note: Closing the response.Body is left to the caller.
func (h apiResponse) process(unmarshalInto interface{}) error {
return h.processWithError(unmarshalInto)
}
// processWithError drains the response body, and processes the HTTP status code
// Note: Closing the response.Body is left to the caller.
func (h apiResponse) processWithError(unmarshalInto interface{}) error {
data, err := io.ReadAll(h.Response.Body)
if err != nil {
return fmt.Errorf("unable to process API response: %w", err)
}
if h.isSuccess() || h.isRedirection() {
if unmarshalInto != nil {
if err := json.Unmarshal(data, unmarshalInto); err != nil {
return fmt.Errorf("unmarshalling into %#v, data %q: %w", unmarshalInto, string(data), err)
}
return nil
}
return nil
}
if h.isInformational() {
return nil
}
return handleError(h.Response.StatusCode, data)
}
func handleError(statusCode int, data []byte) error {
errorModel := httpModelError{
Message: fmt.Sprintf("%s %s", http.StatusText(statusCode), data),
}
return errorModel
}