| 1 |
package goreq |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"bytes" |
| 6 |
"compress/gzip" |
| 7 |
"compress/zlib" |
| 8 |
"crypto/tls" |
| 9 |
"encoding/json" |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"io" |
| 13 |
"io/ioutil" |
| 14 |
"log" |
| 15 |
"net" |
| 16 |
"net/http" |
| 17 |
"net/http/httputil" |
| 18 |
"net/url" |
| 19 |
"reflect" |
| 20 |
"strings" |
| 21 |
"time" |
| 22 |
) |
| 23 |
|
| 24 |
type itimeout interface { |
| 25 |
Timeout() bool |
| 26 |
} |
| 27 |
type Request struct { |
| 28 |
headers []headerTuple |
| 29 |
cookies []*http.Cookie |
| 30 |
Method string |
| 31 |
Uri string |
| 32 |
Body interface{} |
| 33 |
QueryString interface{} |
| 34 |
Timeout time.Duration |
| 35 |
ContentType string |
| 36 |
Accept string |
| 37 |
Host string |
| 38 |
UserAgent string |
| 39 |
Insecure bool |
| 40 |
MaxRedirects int |
| 41 |
RedirectHeaders bool |
| 42 |
Proxy string |
| 43 |
proxyConnectHeaders []headerTuple |
| 44 |
Compression *compression |
| 45 |
BasicAuthUsername string |
| 46 |
BasicAuthPassword string |
| 47 |
CookieJar http.CookieJar |
| 48 |
ShowDebug bool |
| 49 |
OnBeforeRequest func(goreq *Request, httpreq *http.Request) |
| 50 |
} |
| 51 |
|
| 52 |
type compression struct { |
| 53 |
writer func(buffer io.Writer) (io.WriteCloser, error) |
| 54 |
reader func(buffer io.Reader) (io.ReadCloser, error) |
| 55 |
ContentEncoding string |
| 56 |
} |
| 57 |
|
| 58 |
type Response struct { |
| 59 |
*http.Response |
| 60 |
Uri string |
| 61 |
Body *Body |
| 62 |
req *http.Request |
| 63 |
} |
| 64 |
|
| 65 |
func (r Response) CancelRequest() { |
| 66 |
cancelRequest(DefaultTransport, r.req) |
| 67 |
|
| 68 |
} |
| 69 |
|
| 70 |
func cancelRequest(transport interface{}, r *http.Request) { |
| 71 |
if tp, ok := transport.(transportRequestCanceler); ok { |
| 72 |
tp.CancelRequest(r) |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
type headerTuple struct { |
| 77 |
name string |
| 78 |
value string |
| 79 |
} |
| 80 |
|
| 81 |
type Body struct { |
| 82 |
reader io.ReadCloser |
| 83 |
compressedReader io.ReadCloser |
| 84 |
} |
| 85 |
|
| 86 |
type Error struct { |
| 87 |
timeout bool |
| 88 |
Err error |
| 89 |
} |
| 90 |
|
| 91 |
type transportRequestCanceler interface { |
| 92 |
CancelRequest(*http.Request) |
| 93 |
} |
| 94 |
|
| 95 |
func (e *Error) Timeout() bool { |
| 96 |
return e.timeout |
| 97 |
} |
| 98 |
|
| 99 |
func (e *Error) Error() string { |
| 100 |
return e.Err.Error() |
| 101 |
} |
| 102 |
|
| 103 |
func (b *Body) Read(p []byte) (int, error) { |
| 104 |
if b.compressedReader != nil { |
| 105 |
return b.compressedReader.Read(p) |
| 106 |
} |
| 107 |
return b.reader.Read(p) |
| 108 |
} |
| 109 |
|
| 110 |
func (b *Body) Close() error { |
| 111 |
err := b.reader.Close() |
| 112 |
if b.compressedReader != nil { |
| 113 |
return b.compressedReader.Close() |
| 114 |
} |
| 115 |
return err |
| 116 |
} |
| 117 |
|
| 118 |
func (b *Body) FromJsonTo(o interface{}) error { |
| 119 |
return json.NewDecoder(b).Decode(o) |
| 120 |
} |
| 121 |
|
| 122 |
func (b *Body) ToString() (string, error) { |
| 123 |
body, err := ioutil.ReadAll(b) |
| 124 |
if err != nil { |
| 125 |
return "", err |
| 126 |
} |
| 127 |
return string(body), nil |
| 128 |
} |
| 129 |
|
| 130 |
func Gzip() *compression { |
| 131 |
reader := func(buffer io.Reader) (io.ReadCloser, error) { |
| 132 |
return gzip.NewReader(buffer) |
| 133 |
} |
| 134 |
writer := func(buffer io.Writer) (io.WriteCloser, error) { |
| 135 |
return gzip.NewWriter(buffer), nil |
| 136 |
} |
| 137 |
return &compression{writer: writer, reader: reader, ContentEncoding: "gzip"} |
| 138 |
} |
| 139 |
|
| 140 |
func Deflate() *compression { |
| 141 |
reader := func(buffer io.Reader) (io.ReadCloser, error) { |
| 142 |
return zlib.NewReader(buffer) |
| 143 |
} |
| 144 |
writer := func(buffer io.Writer) (io.WriteCloser, error) { |
| 145 |
return zlib.NewWriter(buffer), nil |
| 146 |
} |
| 147 |
return &compression{writer: writer, reader: reader, ContentEncoding: "deflate"} |
| 148 |
} |
| 149 |
|
| 150 |
func Zlib() *compression { |
| 151 |
return Deflate() |
| 152 |
} |
| 153 |
|
| 154 |
func paramParse(query interface{}) (string, error) { |
| 155 |
switch query.(type) { |
| 156 |
case url.Values: |
| 157 |
return query.(url.Values).Encode(), nil |
| 158 |
case *url.Values: |
| 159 |
return query.(*url.Values).Encode(), nil |
| 160 |
default: |
| 161 |
var v = &url.Values{} |
| 162 |
err := paramParseStruct(v, query) |
| 163 |
return v.Encode(), err |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
func paramParseStruct(v *url.Values, query interface{}) error { |
| 168 |
var ( |
| 169 |
s = reflect.ValueOf(query) |
| 170 |
t = reflect.TypeOf(query) |
| 171 |
) |
| 172 |
for t.Kind() == reflect.Ptr || t.Kind() == reflect.Interface { |
| 173 |
s = s.Elem() |
| 174 |
t = s.Type() |
| 175 |
} |
| 176 |
|
| 177 |
if t.Kind() != reflect.Struct { |
| 178 |
return errors.New("Can not parse QueryString.") |
| 179 |
} |
| 180 |
|
| 181 |
for i := 0; i < t.NumField(); i++ { |
| 182 |
var name string |
| 183 |
|
| 184 |
field := s.Field(i) |
| 185 |
typeField := t.Field(i) |
| 186 |
|
| 187 |
if !field.CanInterface() { |
| 188 |
continue |
| 189 |
} |
| 190 |
|
| 191 |
urlTag := typeField.Tag.Get("url") |
| 192 |
if urlTag == "-" { |
| 193 |
continue |
| 194 |
} |
| 195 |
|
| 196 |
name, opts := parseTag(urlTag) |
| 197 |
|
| 198 |
var omitEmpty, squash bool |
| 199 |
omitEmpty = opts.Contains("omitempty") |
| 200 |
squash = opts.Contains("squash") |
| 201 |
|
| 202 |
if squash { |
| 203 |
err := paramParseStruct(v, field.Interface()) |
| 204 |
if err != nil { |
| 205 |
return err |
| 206 |
} |
| 207 |
continue |
| 208 |
} |
| 209 |
|
| 210 |
if urlTag == "" { |
| 211 |
name = strings.ToLower(typeField.Name) |
| 212 |
} |
| 213 |
|
| 214 |
if val := fmt.Sprintf("%v", field.Interface()); !(omitEmpty && len(val) == 0) { |
| 215 |
v.Add(name, val) |
| 216 |
} |
| 217 |
} |
| 218 |
return nil |
| 219 |
} |
| 220 |
|
| 221 |
func prepareRequestBody(b interface{}) (io.Reader, error) { |
| 222 |
switch b.(type) { |
| 223 |
case string: |
| 224 |
// treat is as text |
| 225 |
return strings.NewReader(b.(string)), nil |
| 226 |
case io.Reader: |
| 227 |
// treat is as text |
| 228 |
return b.(io.Reader), nil |
| 229 |
case []byte: |
| 230 |
//treat as byte array |
| 231 |
return bytes.NewReader(b.([]byte)), nil |
| 232 |
case nil: |
| 233 |
return nil, nil |
| 234 |
default: |
| 235 |
// try to jsonify it |
| 236 |
j, err := json.Marshal(b) |
| 237 |
if err == nil { |
| 238 |
return bytes.NewReader(j), nil |
| 239 |
} |
| 240 |
return nil, err |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
var DefaultDialer = &net.Dialer{Timeout: 1000 * time.Millisecond} |
| 245 |
var DefaultTransport http.RoundTripper = &http.Transport{Dial: DefaultDialer.Dial, Proxy: http.ProxyFromEnvironment} |
| 246 |
var DefaultClient = &http.Client{Transport: DefaultTransport} |
| 247 |
|
| 248 |
var proxyTransport http.RoundTripper |
| 249 |
var proxyClient *http.Client |
| 250 |
|
| 251 |
func SetConnectTimeout(duration time.Duration) { |
| 252 |
DefaultDialer.Timeout = duration |
| 253 |
} |
| 254 |
|
| 255 |
func (r *Request) AddHeader(name string, value string) { |
| 256 |
if r.headers == nil { |
| 257 |
r.headers = []headerTuple{} |
| 258 |
} |
| 259 |
r.headers = append(r.headers, headerTuple{name: name, value: value}) |
| 260 |
} |
| 261 |
|
| 262 |
func (r Request) WithHeader(name string, value string) Request { |
| 263 |
r.AddHeader(name, value) |
| 264 |
return r |
| 265 |
} |
| 266 |
|
| 267 |
func (r *Request) AddCookie(c *http.Cookie) { |
| 268 |
r.cookies = append(r.cookies, c) |
| 269 |
} |
| 270 |
|
| 271 |
func (r Request) WithCookie(c *http.Cookie) Request { |
| 272 |
r.AddCookie(c) |
| 273 |
return r |
| 274 |
} |
| 275 |
|
| 276 |
func (r *Request) AddProxyConnectHeader(name string, value string) { |
| 277 |
if r.proxyConnectHeaders == nil { |
| 278 |
r.proxyConnectHeaders = []headerTuple{} |
| 279 |
} |
| 280 |
r.proxyConnectHeaders = append(r.proxyConnectHeaders, headerTuple{name: name, value: value}) |
| 281 |
} |
| 282 |
|
| 283 |
func (r Request) WithProxyConnectHeader(name string, value string) Request { |
| 284 |
r.AddProxyConnectHeader(name, value) |
| 285 |
return r |
| 286 |
} |
| 287 |
|
| 288 |
func (r Request) Do() (*Response, error) { |
| 289 |
var client = DefaultClient |
| 290 |
var transport = DefaultTransport |
| 291 |
var resUri string |
| 292 |
var redirectFailed bool |
| 293 |
|
| 294 |
r.Method = valueOrDefault(r.Method, "GET") |
| 295 |
|
| 296 |
// use a client with a cookie jar if necessary. We create a new client not |
| 297 |
// to modify the default one. |
| 298 |
if r.CookieJar != nil { |
| 299 |
client = &http.Client{ |
| 300 |
Transport: transport, |
| 301 |
Jar: r.CookieJar, |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
if r.Proxy != "" { |
| 306 |
proxyUrl, err := url.Parse(r.Proxy) |
| 307 |
if err != nil { |
| 308 |
// proxy address is in a wrong format |
| 309 |
return nil, &Error{Err: err} |
| 310 |
} |
| 311 |
|
| 312 |
proxyHeader := make(http.Header) |
| 313 |
if r.proxyConnectHeaders != nil { |
| 314 |
for _, header := range r.proxyConnectHeaders { |
| 315 |
proxyHeader.Add(header.name, header.value) |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
//If jar is specified new client needs to be built |
| 320 |
if proxyTransport == nil || client.Jar != nil { |
| 321 |
proxyTransport = &http.Transport{ |
| 322 |
Dial: DefaultDialer.Dial, |
| 323 |
Proxy: http.ProxyURL(proxyUrl), |
| 324 |
ProxyConnectHeader: proxyHeader, |
| 325 |
} |
| 326 |
proxyClient = &http.Client{Transport: proxyTransport, Jar: client.Jar} |
| 327 |
} else if proxyTransport, ok := proxyTransport.(*http.Transport); ok { |
| 328 |
proxyTransport.Proxy = http.ProxyURL(proxyUrl) |
| 329 |
proxyTransport.ProxyConnectHeader = proxyHeader |
| 330 |
} |
| 331 |
transport = proxyTransport |
| 332 |
client = proxyClient |
| 333 |
} |
| 334 |
|
| 335 |
client.CheckRedirect = func(req *http.Request, via []*http.Request) error { |
| 336 |
|
| 337 |
if len(via) > r.MaxRedirects { |
| 338 |
redirectFailed = true |
| 339 |
return errors.New("Error redirecting. MaxRedirects reached") |
| 340 |
} |
| 341 |
|
| 342 |
resUri = req.URL.String() |
| 343 |
|
| 344 |
//By default Golang will not redirect request headers |
| 345 |
// https://code.google.com/p/go/issues/detail?id=4800&q=request%20header |
| 346 |
if r.RedirectHeaders { |
| 347 |
for key, val := range via[0].Header { |
| 348 |
req.Header[key] = val |
| 349 |
} |
| 350 |
} |
| 351 |
return nil |
| 352 |
} |
| 353 |
|
| 354 |
if transport, ok := transport.(*http.Transport); ok { |
| 355 |
if r.Insecure { |
| 356 |
if transport.TLSClientConfig != nil { |
| 357 |
transport.TLSClientConfig.InsecureSkipVerify = true |
| 358 |
} else { |
| 359 |
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} |
| 360 |
} |
| 361 |
} else if transport.TLSClientConfig != nil { |
| 362 |
// the default TLS client (when transport.TLSClientConfig==nil) is |
| 363 |
// already set to verify, so do nothing in that case |
| 364 |
transport.TLSClientConfig.InsecureSkipVerify = false |
| 365 |
} |
| 366 |
} |
| 367 |
|
| 368 |
req, err := r.NewRequest() |
| 369 |
|
| 370 |
if err != nil { |
| 371 |
// we couldn't parse the URL. |
| 372 |
return nil, &Error{Err: err} |
| 373 |
} |
| 374 |
|
| 375 |
timeout := false |
| 376 |
if r.Timeout > 0 { |
| 377 |
client.Timeout = r.Timeout |
| 378 |
} |
| 379 |
|
| 380 |
if r.ShowDebug { |
| 381 |
dump, err := httputil.DumpRequest(req, true) |
| 382 |
if err != nil { |
| 383 |
log.Println(err) |
| 384 |
} |
| 385 |
log.Println(string(dump)) |
| 386 |
} |
| 387 |
|
| 388 |
if r.OnBeforeRequest != nil { |
| 389 |
r.OnBeforeRequest(&r, req) |
| 390 |
} |
| 391 |
res, err := client.Do(req) |
| 392 |
|
| 393 |
if err != nil { |
| 394 |
if !timeout { |
| 395 |
if t, ok := err.(itimeout); ok { |
| 396 |
timeout = t.Timeout() |
| 397 |
} |
| 398 |
if ue, ok := err.(*url.Error); ok { |
| 399 |
if t, ok := ue.Err.(itimeout); ok { |
| 400 |
timeout = t.Timeout() |
| 401 |
} |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
var response *Response |
| 406 |
//If redirect fails we still want to return response data |
| 407 |
if redirectFailed { |
| 408 |
if res != nil { |
| 409 |
response = &Response{res, resUri, &Body{reader: res.Body}, req} |
| 410 |
} else { |
| 411 |
response = &Response{res, resUri, nil, req} |
| 412 |
} |
| 413 |
} |
| 414 |
|
| 415 |
//If redirect fails and we haven't set a redirect count we shouldn't return an error |
| 416 |
if redirectFailed && r.MaxRedirects == 0 { |
| 417 |
return response, nil |
| 418 |
} |
| 419 |
|
| 420 |
return response, &Error{timeout: timeout, Err: err} |
| 421 |
} |
| 422 |
|
| 423 |
if r.Compression != nil && strings.Contains(res.Header.Get("Content-Encoding"), r.Compression.ContentEncoding) { |
| 424 |
compressedReader, err := r.Compression.reader(res.Body) |
| 425 |
if err != nil { |
| 426 |
return nil, &Error{Err: err} |
| 427 |
} |
| 428 |
return &Response{res, resUri, &Body{reader: res.Body, compressedReader: compressedReader}, req}, nil |
| 429 |
} |
| 430 |
|
| 431 |
return &Response{res, resUri, &Body{reader: res.Body}, req}, nil |
| 432 |
} |
| 433 |
|
| 434 |
func (r Request) addHeaders(headersMap http.Header) { |
| 435 |
if len(r.UserAgent) > 0 { |
| 436 |
headersMap.Add("User-Agent", r.UserAgent) |
| 437 |
} |
| 438 |
if r.Accept != "" { |
| 439 |
headersMap.Add("Accept", r.Accept) |
| 440 |
} |
| 441 |
if r.ContentType != "" { |
| 442 |
headersMap.Add("Content-Type", r.ContentType) |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
func (r Request) NewRequest() (*http.Request, error) { |
| 447 |
|
| 448 |
b, e := prepareRequestBody(r.Body) |
| 449 |
if e != nil { |
| 450 |
// there was a problem marshaling the body |
| 451 |
return nil, &Error{Err: e} |
| 452 |
} |
| 453 |
|
| 454 |
if r.QueryString != nil { |
| 455 |
param, e := paramParse(r.QueryString) |
| 456 |
if e != nil { |
| 457 |
return nil, &Error{Err: e} |
| 458 |
} |
| 459 |
r.Uri = r.Uri + "?" + param |
| 460 |
} |
| 461 |
|
| 462 |
var bodyReader io.Reader |
| 463 |
if b != nil && r.Compression != nil { |
| 464 |
buffer := bytes.NewBuffer([]byte{}) |
| 465 |
readBuffer := bufio.NewReader(b) |
| 466 |
writer, err := r.Compression.writer(buffer) |
| 467 |
if err != nil { |
| 468 |
return nil, &Error{Err: err} |
| 469 |
} |
| 470 |
_, e = readBuffer.WriteTo(writer) |
| 471 |
writer.Close() |
| 472 |
if e != nil { |
| 473 |
return nil, &Error{Err: e} |
| 474 |
} |
| 475 |
bodyReader = buffer |
| 476 |
} else { |
| 477 |
bodyReader = b |
| 478 |
} |
| 479 |
|
| 480 |
req, err := http.NewRequest(r.Method, r.Uri, bodyReader) |
| 481 |
if err != nil { |
| 482 |
return nil, err |
| 483 |
} |
| 484 |
// add headers to the request |
| 485 |
req.Host = r.Host |
| 486 |
|
| 487 |
r.addHeaders(req.Header) |
| 488 |
if r.Compression != nil { |
| 489 |
req.Header.Add("Content-Encoding", r.Compression.ContentEncoding) |
| 490 |
req.Header.Add("Accept-Encoding", r.Compression.ContentEncoding) |
| 491 |
} |
| 492 |
if r.headers != nil { |
| 493 |
for _, header := range r.headers { |
| 494 |
req.Header.Add(header.name, header.value) |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
//use basic auth if required |
| 499 |
if r.BasicAuthUsername != "" { |
| 500 |
req.SetBasicAuth(r.BasicAuthUsername, r.BasicAuthPassword) |
| 501 |
} |
| 502 |
|
| 503 |
for _, c := range r.cookies { |
| 504 |
req.AddCookie(c) |
| 505 |
} |
| 506 |
return req, nil |
| 507 |
} |
| 508 |
|
| 509 |
// Return value if nonempty, def otherwise. |
| 510 |
func valueOrDefault(value, def string) string { |
| 511 |
if value != "" { |
| 512 |
return value |
| 513 |
} |
| 514 |
return def |
| 515 |
} |