forked from nsqio/nsq
/
api_request.go
213 lines (185 loc) · 4.51 KB
/
api_request.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package http_api
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type deadlinedConn struct {
Timeout time.Duration
net.Conn
}
func (c *deadlinedConn) Read(b []byte) (n int, err error) {
c.Conn.SetReadDeadline(time.Now().Add(c.Timeout))
return c.Conn.Read(b)
}
func (c *deadlinedConn) Write(b []byte) (n int, err error) {
c.Conn.SetWriteDeadline(time.Now().Add(c.Timeout))
return c.Conn.Write(b)
}
// A custom http.Transport with support for deadline timeouts
func NewDeadlineTransport(timeout time.Duration) *http.Transport {
transport := &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, timeout)
if err != nil {
return nil, err
}
return &deadlinedConn{timeout, c}, nil
},
}
return transport
}
type Client struct {
c *http.Client
}
func NewClient(tlsConfig *tls.Config) *Client {
transport := NewDeadlineTransport(2 * time.Second)
transport.TLSClientConfig = tlsConfig
return &Client{
c: &http.Client{
Transport: transport,
},
}
}
// NegotiateV1 is a helper function to perform a v1 HTTP request
// and fallback to parsing the old backwards-compatible response format
// storing the result in the value pointed to by v.
//
// TODO: deprecated, remove in 1.0 (replace calls with GETV1)
func (c *Client) NegotiateV1(endpoint string, v interface{}) error {
retry:
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return err
}
req.Header.Add("Accept", "application/vnd.nsq; version=1.0")
resp, err := c.c.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
if resp.StatusCode != 200 {
if resp.StatusCode == 403 && !strings.HasPrefix(endpoint, "https") {
endpoint, err = httpsEndpoint(endpoint, body)
if err != nil {
return err
}
goto retry
}
return fmt.Errorf("got response %s %q", resp.Status, body)
}
if len(body) == 0 {
body = []byte("{}")
}
// unwrap pre-1.0 api response
if resp.Header.Get("X-NSQ-Content-Type") != "nsq; version=1.0" {
var u struct {
StatusCode int64 `json:"status_code"`
Data json.RawMessage `json:"data"`
}
err := json.Unmarshal(body, u)
if err != nil {
return err
}
if u.StatusCode != 200 {
return fmt.Errorf("got 200 response, but api status code of %d", u.StatusCode)
}
body = u.Data
}
return json.Unmarshal(body, v)
}
// GETV1 is a helper function to perform a V1 HTTP request
// and parse our NSQ daemon's expected response format, with deadlines.
func (c *Client) GETV1(endpoint string, v interface{}) error {
retry:
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return err
}
req.Header.Add("Accept", "application/vnd.nsq; version=1.0")
resp, err := c.c.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
if resp.StatusCode != 200 {
if resp.StatusCode == 403 && !strings.HasPrefix(endpoint, "https") {
endpoint, err = httpsEndpoint(endpoint, body)
if err != nil {
return err
}
goto retry
}
return fmt.Errorf("got response %s %q", resp.Status, body)
}
err = json.Unmarshal(body, &v)
if err != nil {
return err
}
return nil
}
// PostV1 is a helper function to perform a V1 HTTP request
// and parse our NSQ daemon's expected response format, with deadlines.
func (c *Client) POSTV1(endpoint string) error {
retry:
req, err := http.NewRequest("POST", endpoint, nil)
if err != nil {
return err
}
req.Header.Add("Accept", "application/vnd.nsq; version=1.0")
resp, err := c.c.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
if resp.StatusCode != 200 {
if resp.StatusCode == 403 && !strings.HasPrefix(endpoint, "https") {
endpoint, err = httpsEndpoint(endpoint, body)
if err != nil {
return err
}
goto retry
}
return fmt.Errorf("got response %s %q", resp.Status, body)
}
return nil
}
func httpsEndpoint(endpoint string, body []byte) (string, error) {
var forbiddenResp struct {
HTTPSPort int `json:"https_port"`
}
err := json.Unmarshal(body, &forbiddenResp)
if err != nil {
return "", err
}
u, err := url.Parse(endpoint)
if err != nil {
return "", err
}
host, _, err := net.SplitHostPort(u.Host)
if err != nil {
return "", err
}
u.Scheme = "https"
u.Host = net.JoinHostPort(host, strconv.Itoa(forbiddenResp.HTTPSPort))
return u.String(), nil
}