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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
|
// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"bytes"
"compress/gzip"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"os"
"reflect"
"regexp"
"strings"
"sync"
"time"
)
const (
// MethodGet HTTP method
MethodGet = "GET"
// MethodPost HTTP method
MethodPost = "POST"
// MethodPut HTTP method
MethodPut = "PUT"
// MethodDelete HTTP method
MethodDelete = "DELETE"
// MethodPatch HTTP method
MethodPatch = "PATCH"
// MethodHead HTTP method
MethodHead = "HEAD"
// MethodOptions HTTP method
MethodOptions = "OPTIONS"
)
var (
hdrUserAgentKey = http.CanonicalHeaderKey("User-Agent")
hdrAcceptKey = http.CanonicalHeaderKey("Accept")
hdrContentTypeKey = http.CanonicalHeaderKey("Content-Type")
hdrContentLengthKey = http.CanonicalHeaderKey("Content-Length")
hdrContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding")
hdrLocationKey = http.CanonicalHeaderKey("Location")
hdrAuthorizationKey = http.CanonicalHeaderKey("Authorization")
hdrWwwAuthenticateKey = http.CanonicalHeaderKey("WWW-Authenticate")
plainTextType = "text/plain; charset=utf-8"
jsonContentType = "application/json"
formContentType = "application/x-www-form-urlencoded"
jsonCheck = regexp.MustCompile(`(?i:(application|text)/(.*json.*)(;|$))`)
xmlCheck = regexp.MustCompile(`(?i:(application|text)/(.*xml.*)(;|$))`)
hdrUserAgentValue = "go-resty/" + Version + " (https://github.com/go-resty/resty)"
bufPool = &sync.Pool{New: func() interface{} { return &bytes.Buffer{} }}
)
type (
// RequestMiddleware type is for request middleware, called before a request is sent
RequestMiddleware func(*Client, *Request) error
// ResponseMiddleware type is for response middleware, called after a response has been received
ResponseMiddleware func(*Client, *Response) error
// PreRequestHook type is for the request hook, called right before the request is sent
PreRequestHook func(*Client, *http.Request) error
// RequestLogCallback type is for request logs, called before the request is logged
RequestLogCallback func(*RequestLog) error
// ResponseLogCallback type is for response logs, called before the response is logged
ResponseLogCallback func(*ResponseLog) error
// ErrorHook type is for reacting to request errors, called after all retries were attempted
ErrorHook func(*Request, error)
// SuccessHook type is for reacting to request success
SuccessHook func(*Client, *Response)
)
// Client struct is used to create Resty client with client level settings,
// these settings are applicable to all the request raised from the client.
//
// Resty also provides an options to override most of the client settings
// at request level.
type Client struct {
BaseURL string
HostURL string // Deprecated: use BaseURL instead. To be removed in v3.0.0 release.
QueryParam url.Values
FormData url.Values
PathParams map[string]string
RawPathParams map[string]string
Header http.Header
UserInfo *User
Token string
AuthScheme string
Cookies []*http.Cookie
Error reflect.Type
Debug bool
DisableWarn bool
AllowGetMethodPayload bool
RetryCount int
RetryWaitTime time.Duration
RetryMaxWaitTime time.Duration
RetryConditions []RetryConditionFunc
RetryHooks []OnRetryFunc
RetryAfter RetryAfterFunc
RetryResetReaders bool
JSONMarshal func(v interface{}) ([]byte, error)
JSONUnmarshal func(data []byte, v interface{}) error
XMLMarshal func(v interface{}) ([]byte, error)
XMLUnmarshal func(data []byte, v interface{}) error
// HeaderAuthorizationKey is used to set/access Request Authorization header
// value when `SetAuthToken` option is used.
HeaderAuthorizationKey string
jsonEscapeHTML bool
setContentLength bool
closeConnection bool
notParseResponse bool
trace bool
debugBodySizeLimit int64
outputDirectory string
scheme string
log Logger
httpClient *http.Client
proxyURL *url.URL
beforeRequest []RequestMiddleware
udBeforeRequest []RequestMiddleware
udBeforeRequestLock sync.RWMutex
preReqHook PreRequestHook
successHooks []SuccessHook
afterResponse []ResponseMiddleware
afterResponseLock sync.RWMutex
requestLog RequestLogCallback
responseLog ResponseLogCallback
errorHooks []ErrorHook
invalidHooks []ErrorHook
panicHooks []ErrorHook
rateLimiter RateLimiter
}
// User type is to hold an username and password information
type User struct {
Username, Password string
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Client methods
//___________________________________
// SetHostURL method is to set Host URL in the client instance. It will be used with request
// raised from this client with relative URL
//
// // Setting HTTP address
// client.SetHostURL("http://myjeeva.com")
//
// // Setting HTTPS address
// client.SetHostURL("https://myjeeva.com")
//
// Deprecated: use SetBaseURL instead. To be removed in v3.0.0 release.
func (c *Client) SetHostURL(url string) *Client {
c.SetBaseURL(url)
return c
}
// SetBaseURL method is to set Base URL in the client instance. It will be used with request
// raised from this client with relative URL
//
// // Setting HTTP address
// client.SetBaseURL("http://myjeeva.com")
//
// // Setting HTTPS address
// client.SetBaseURL("https://myjeeva.com")
//
// Since v2.7.0
func (c *Client) SetBaseURL(url string) *Client {
c.BaseURL = strings.TrimRight(url, "/")
c.HostURL = c.BaseURL
return c
}
// SetHeader method sets a single header field and its value in the client instance.
// These headers will be applied to all requests raised from this client instance.
// Also it can be overridden at request level header options.
//
// See `Request.SetHeader` or `Request.SetHeaders`.
//
// For Example: To set `Content-Type` and `Accept` as `application/json`
//
// client.
// SetHeader("Content-Type", "application/json").
// SetHeader("Accept", "application/json")
func (c *Client) SetHeader(header, value string) *Client {
c.Header.Set(header, value)
return c
}
// SetHeaders method sets multiple headers field and its values at one go in the client instance.
// These headers will be applied to all requests raised from this client instance. Also it can be
// overridden at request level headers options.
//
// See `Request.SetHeaders` or `Request.SetHeader`.
//
// For Example: To set `Content-Type` and `Accept` as `application/json`
//
// client.SetHeaders(map[string]string{
// "Content-Type": "application/json",
// "Accept": "application/json",
// })
func (c *Client) SetHeaders(headers map[string]string) *Client {
for h, v := range headers {
c.Header.Set(h, v)
}
return c
}
// SetHeaderVerbatim method is to set a single header field and its value verbatim in the current request.
//
// For Example: To set `all_lowercase` and `UPPERCASE` as `available`.
//
// client.R().
// SetHeaderVerbatim("all_lowercase", "available").
// SetHeaderVerbatim("UPPERCASE", "available")
//
// Also you can override header value, which was set at client instance level.
//
// Since v2.6.0
func (c *Client) SetHeaderVerbatim(header, value string) *Client {
c.Header[header] = []string{value}
return c
}
// SetCookieJar method sets custom http.CookieJar in the resty client. Its way to override default.
//
// For Example: sometimes we don't want to save cookies in api contacting, we can remove the default
// CookieJar in resty client.
//
// client.SetCookieJar(nil)
func (c *Client) SetCookieJar(jar http.CookieJar) *Client {
c.httpClient.Jar = jar
return c
}
// SetCookie method appends a single cookie in the client instance.
// These cookies will be added to all the request raised from this client instance.
//
// client.SetCookie(&http.Cookie{
// Name:"go-resty",
// Value:"This is cookie value",
// })
func (c *Client) SetCookie(hc *http.Cookie) *Client {
c.Cookies = append(c.Cookies, hc)
return c
}
// SetCookies method sets an array of cookies in the client instance.
// These cookies will be added to all the request raised from this client instance.
//
// cookies := []*http.Cookie{
// &http.Cookie{
// Name:"go-resty-1",
// Value:"This is cookie 1 value",
// },
// &http.Cookie{
// Name:"go-resty-2",
// Value:"This is cookie 2 value",
// },
// }
//
// // Setting a cookies into resty
// client.SetCookies(cookies)
func (c *Client) SetCookies(cs []*http.Cookie) *Client {
c.Cookies = append(c.Cookies, cs...)
return c
}
// SetQueryParam method sets single parameter and its value in the client instance.
// It will be formed as query string for the request.
//
// For Example: `search=kitchen%20papers&size=large`
// in the URL after `?` mark. These query params will be added to all the request raised from
// this client instance. Also it can be overridden at request level Query Param options.
//
// See `Request.SetQueryParam` or `Request.SetQueryParams`.
//
// client.
// SetQueryParam("search", "kitchen papers").
// SetQueryParam("size", "large")
func (c *Client) SetQueryParam(param, value string) *Client {
c.QueryParam.Set(param, value)
return c
}
// SetQueryParams method sets multiple parameters and their values at one go in the client instance.
// It will be formed as query string for the request.
//
// For Example: `search=kitchen%20papers&size=large`
// in the URL after `?` mark. These query params will be added to all the request raised from this
// client instance. Also it can be overridden at request level Query Param options.
//
// See `Request.SetQueryParams` or `Request.SetQueryParam`.
//
// client.SetQueryParams(map[string]string{
// "search": "kitchen papers",
// "size": "large",
// })
func (c *Client) SetQueryParams(params map[string]string) *Client {
for p, v := range params {
c.SetQueryParam(p, v)
}
return c
}
// SetFormData method sets Form parameters and their values in the client instance.
// It's applicable only HTTP method `POST` and `PUT` and request content type would be set as
// `application/x-www-form-urlencoded`. These form data will be added to all the request raised from
// this client instance. Also it can be overridden at request level form data.
//
// See `Request.SetFormData`.
//
// client.SetFormData(map[string]string{
// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
// "user_id": "3455454545",
// })
func (c *Client) SetFormData(data map[string]string) *Client {
for k, v := range data {
c.FormData.Set(k, v)
}
return c
}
// SetBasicAuth method sets the basic authentication header in the HTTP request. For Example:
//
// Authorization: Basic <base64-encoded-value>
//
// For Example: To set the header for username "go-resty" and password "welcome"
//
// client.SetBasicAuth("go-resty", "welcome")
//
// This basic auth information gets added to all the request raised from this client instance.
// Also it can be overridden or set one at the request level is supported.
//
// See `Request.SetBasicAuth`.
func (c *Client) SetBasicAuth(username, password string) *Client {
c.UserInfo = &User{Username: username, Password: password}
return c
}
// SetAuthToken method sets the auth token of the `Authorization` header for all HTTP requests.
// The default auth scheme is `Bearer`, it can be customized with the method `SetAuthScheme`. For Example:
//
// Authorization: <auth-scheme> <auth-token-value>
//
// For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
//
// client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
//
// This auth token gets added to all the requests raised from this client instance.
// Also it can be overridden or set one at the request level is supported.
//
// See `Request.SetAuthToken`.
func (c *Client) SetAuthToken(token string) *Client {
c.Token = token
return c
}
// SetAuthScheme method sets the auth scheme type in the HTTP request. For Example:
//
// Authorization: <auth-scheme-value> <auth-token-value>
//
// For Example: To set the scheme to use OAuth
//
// client.SetAuthScheme("OAuth")
//
// This auth scheme gets added to all the requests raised from this client instance.
// Also it can be overridden or set one at the request level is supported.
//
// Information about auth schemes can be found in RFC7235 which is linked to below
// along with the page containing the currently defined official authentication schemes:
//
// https://tools.ietf.org/html/rfc7235
// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes
//
// See `Request.SetAuthToken`.
func (c *Client) SetAuthScheme(scheme string) *Client {
c.AuthScheme = scheme
return c
}
// SetDigestAuth method sets the Digest Access auth scheme for the client. If a server responds with 401 and sends
// a Digest challenge in the WWW-Authenticate Header, requests will be resent with the appropriate Authorization Header.
//
// For Example: To set the Digest scheme with user "Mufasa" and password "Circle Of Life"
//
// client.SetDigestAuth("Mufasa", "Circle Of Life")
//
// Information about Digest Access Authentication can be found in RFC7616:
//
// https://datatracker.ietf.org/doc/html/rfc7616
//
// See `Request.SetDigestAuth`.
func (c *Client) SetDigestAuth(username, password string) *Client {
oldTransport := c.httpClient.Transport
c.OnBeforeRequest(func(c *Client, _ *Request) error {
c.httpClient.Transport = &digestTransport{
digestCredentials: digestCredentials{username, password},
transport: oldTransport,
}
return nil
})
c.OnAfterResponse(func(c *Client, _ *Response) error {
c.httpClient.Transport = oldTransport
return nil
})
return c
}
// R method creates a new request instance, its used for Get, Post, Put, Delete, Patch, Head, Options, etc.
func (c *Client) R() *Request {
r := &Request{
QueryParam: url.Values{},
FormData: url.Values{},
Header: http.Header{},
Cookies: make([]*http.Cookie, 0),
PathParams: map[string]string{},
RawPathParams: map[string]string{},
Debug: c.Debug,
client: c,
multipartFiles: []*File{},
multipartFields: []*MultipartField{},
jsonEscapeHTML: c.jsonEscapeHTML,
log: c.log,
}
return r
}
// NewRequest is an alias for method `R()`. Creates a new request instance, its used for
// Get, Post, Put, Delete, Patch, Head, Options, etc.
func (c *Client) NewRequest() *Request {
return c.R()
}
// OnBeforeRequest method appends a request middleware into the before request chain.
// The user defined middlewares get applied before the default Resty request middlewares.
// After all middlewares have been applied, the request is sent from Resty to the host server.
//
// client.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error {
// // Now you have access to Client and Request instance
// // manipulate it as per your need
//
// return nil // if its success otherwise return error
// })
func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client {
c.udBeforeRequestLock.Lock()
defer c.udBeforeRequestLock.Unlock()
c.udBeforeRequest = append(c.udBeforeRequest, m)
return c
}
// OnAfterResponse method appends response middleware into the after response chain.
// Once we receive response from host server, default Resty response middleware
// gets applied and then user assigned response middlewares applied.
//
// client.OnAfterResponse(func(c *resty.Client, r *resty.Response) error {
// // Now you have access to Client and Response instance
// // manipulate it as per your need
//
// return nil // if its success otherwise return error
// })
func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client {
c.afterResponseLock.Lock()
defer c.afterResponseLock.Unlock()
c.afterResponse = append(c.afterResponse, m)
return c
}
// OnError method adds a callback that will be run whenever a request execution fails.
// This is called after all retries have been attempted (if any).
// If there was a response from the server, the error will be wrapped in *ResponseError
// which has the last response received from the server.
//
// client.OnError(func(req *resty.Request, err error) {
// if v, ok := err.(*resty.ResponseError); ok {
// // Do something with v.Response
// }
// // Log the error, increment a metric, etc...
// })
//
// Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one
// set will be invoked for each call to Request.Execute() that completes.
func (c *Client) OnError(h ErrorHook) *Client {
c.errorHooks = append(c.errorHooks, h)
return c
}
// OnSuccess method adds a callback that will be run whenever a request execution
// succeeds. This is called after all retries have been attempted (if any).
//
// Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one
// set will be invoked for each call to Request.Execute() that completes.
//
// Since v2.8.0
func (c *Client) OnSuccess(h SuccessHook) *Client {
c.successHooks = append(c.successHooks, h)
return c
}
// OnInvalid method adds a callback that will be run whenever a request execution
// fails before it starts because the request is invalid.
//
// Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one
// set will be invoked for each call to Request.Execute() that completes.
//
// Since v2.8.0
func (c *Client) OnInvalid(h ErrorHook) *Client {
c.invalidHooks = append(c.invalidHooks, h)
return c
}
// OnPanic method adds a callback that will be run whenever a request execution
// panics.
//
// Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one
// set will be invoked for each call to Request.Execute() that completes.
// If an OnSuccess, OnError, or OnInvalid callback panics, then the exactly
// one rule can be violated.
//
// Since v2.8.0
func (c *Client) OnPanic(h ErrorHook) *Client {
c.panicHooks = append(c.panicHooks, h)
return c
}
// SetPreRequestHook method sets the given pre-request function into resty client.
// It is called right before the request is fired.
//
// Note: Only one pre-request hook can be registered. Use `client.OnBeforeRequest` for multiple.
func (c *Client) SetPreRequestHook(h PreRequestHook) *Client {
if c.preReqHook != nil {
c.log.Warnf("Overwriting an existing pre-request hook: %s", functionName(h))
}
c.preReqHook = h
return c
}
// SetDebug method enables the debug mode on Resty client. Client logs details of every request and response.
// For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one.
// For `Response` it logs information such as Status, Response Time, Headers, Body if it has one.
//
// client.SetDebug(true)
//
// Also it can be enabled at request level for particular request, see `Request.SetDebug`.
func (c *Client) SetDebug(d bool) *Client {
c.Debug = d
return c
}
// SetDebugBodyLimit sets the maximum size for which the response and request body will be logged in debug mode.
//
// client.SetDebugBodyLimit(1000000)
func (c *Client) SetDebugBodyLimit(sl int64) *Client {
c.debugBodySizeLimit = sl
return c
}
// OnRequestLog method used to set request log callback into Resty. Registered callback gets
// called before the resty actually logs the information.
func (c *Client) OnRequestLog(rl RequestLogCallback) *Client {
if c.requestLog != nil {
c.log.Warnf("Overwriting an existing on-request-log callback from=%s to=%s",
functionName(c.requestLog), functionName(rl))
}
c.requestLog = rl
return c
}
// OnResponseLog method used to set response log callback into Resty. Registered callback gets
// called before the resty actually logs the information.
func (c *Client) OnResponseLog(rl ResponseLogCallback) *Client {
if c.responseLog != nil {
c.log.Warnf("Overwriting an existing on-response-log callback from=%s to=%s",
functionName(c.responseLog), functionName(rl))
}
c.responseLog = rl
return c
}
// SetDisableWarn method disables the warning message on Resty client.
//
// For Example: Resty warns the user when BasicAuth used on non-TLS mode.
//
// client.SetDisableWarn(true)
func (c *Client) SetDisableWarn(d bool) *Client {
c.DisableWarn = d
return c
}
// SetAllowGetMethodPayload method allows the GET method with payload on Resty client.
//
// For Example: Resty allows the user sends request with a payload on HTTP GET method.
//
// client.SetAllowGetMethodPayload(true)
func (c *Client) SetAllowGetMethodPayload(a bool) *Client {
c.AllowGetMethodPayload = a
return c
}
// SetLogger method sets given writer for logging Resty request and response details.
//
// Compliant to interface `resty.Logger`.
func (c *Client) SetLogger(l Logger) *Client {
c.log = l
return c
}
// SetContentLength method enables the HTTP header `Content-Length` value for every request.
// By default Resty won't set `Content-Length`.
//
// client.SetContentLength(true)
//
// Also you have an option to enable for particular request. See `Request.SetContentLength`
func (c *Client) SetContentLength(l bool) *Client {
c.setContentLength = l
return c
}
// SetTimeout method sets timeout for request raised from client.
//
// client.SetTimeout(time.Duration(1 * time.Minute))
func (c *Client) SetTimeout(timeout time.Duration) *Client {
c.httpClient.Timeout = timeout
return c
}
// SetError method is to register the global or client common `Error` object into Resty.
// It is used for automatic unmarshalling if response status code is greater than 399 and
// content type either JSON or XML. Can be pointer or non-pointer.
//
// client.SetError(&Error{})
// // OR
// client.SetError(Error{})
func (c *Client) SetError(err interface{}) *Client {
c.Error = typeOf(err)
return c
}
// SetRedirectPolicy method sets the client redirect policy. Resty provides ready to use
// redirect policies. Wanna create one for yourself refer to `redirect.go`.
//
// client.SetRedirectPolicy(FlexibleRedirectPolicy(20))
//
// // Need multiple redirect policies together
// client.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net"))
func (c *Client) SetRedirectPolicy(policies ...interface{}) *Client {
for _, p := range policies {
if _, ok := p.(RedirectPolicy); !ok {
c.log.Errorf("%v does not implement resty.RedirectPolicy (missing Apply method)",
functionName(p))
}
}
c.httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
for _, p := range policies {
if err := p.(RedirectPolicy).Apply(req, via); err != nil {
return err
}
}
return nil // looks good, go ahead
}
return c
}
// SetRetryCount method enables retry on Resty client and allows you
// to set no. of retry count. Resty uses a Backoff mechanism.
func (c *Client) SetRetryCount(count int) *Client {
c.RetryCount = count
return c
}
// SetRetryWaitTime method sets default wait time to sleep before retrying
// request.
//
// Default is 100 milliseconds.
func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client {
c.RetryWaitTime = waitTime
return c
}
// SetRetryMaxWaitTime method sets max wait time to sleep before retrying
// request.
//
// Default is 2 seconds.
func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client {
c.RetryMaxWaitTime = maxWaitTime
return c
}
// SetRetryAfter sets callback to calculate wait time between retries.
// Default (nil) implies exponential backoff with jitter
func (c *Client) SetRetryAfter(callback RetryAfterFunc) *Client {
c.RetryAfter = callback
return c
}
// SetJSONMarshaler method sets the JSON marshaler function to marshal the request body.
// By default, Resty uses `encoding/json` package to marshal the request body.
//
// Since v2.8.0
func (c *Client) SetJSONMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client {
c.JSONMarshal = marshaler
return c
}
// SetJSONUnmarshaler method sets the JSON unmarshaler function to unmarshal the response body.
// By default, Resty uses `encoding/json` package to unmarshal the response body.
//
// Since v2.8.0
func (c *Client) SetJSONUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client {
c.JSONUnmarshal = unmarshaler
return c
}
// SetXMLMarshaler method sets the XML marshaler function to marshal the request body.
// By default, Resty uses `encoding/xml` package to marshal the request body.
//
// Since v2.8.0
func (c *Client) SetXMLMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client {
c.XMLMarshal = marshaler
return c
}
// SetXMLUnmarshaler method sets the XML unmarshaler function to unmarshal the response body.
// By default, Resty uses `encoding/xml` package to unmarshal the response body.
//
// Since v2.8.0
func (c *Client) SetXMLUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client {
c.XMLUnmarshal = unmarshaler
return c
}
// AddRetryCondition method adds a retry condition function to array of functions
// that are checked to determine if the request is retried. The request will
// retry if any of the functions return true and error is nil.
//
// Note: These retry conditions are applied on all Request made using this Client.
// For Request specific retry conditions check *Request.AddRetryCondition
func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client {
c.RetryConditions = append(c.RetryConditions, condition)
return c
}
// AddRetryAfterErrorCondition adds the basic condition of retrying after encountering
// an error from the http response
//
// Since v2.6.0
func (c *Client) AddRetryAfterErrorCondition() *Client {
c.AddRetryCondition(func(response *Response, err error) bool {
return response.IsError()
})
return c
}
// AddRetryHook adds a side-effecting retry hook to an array of hooks
// that will be executed on each retry.
//
// Since v2.6.0
func (c *Client) AddRetryHook(hook OnRetryFunc) *Client {
c.RetryHooks = append(c.RetryHooks, hook)
return c
}
// SetRetryResetReaders method enables the Resty client to seek the start of all
// file readers given as multipart files, if the given object implements `io.ReadSeeker`.
//
// Since ...
func (c *Client) SetRetryResetReaders(b bool) *Client {
c.RetryResetReaders = b
return c
}
// SetTLSClientConfig method sets TLSClientConfig for underling client Transport.
//
// For Example:
//
// // One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial
// client.SetTLSClientConfig(&tls.Config{ RootCAs: roots })
//
// // or One can disable security check (https)
// client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true })
//
// Note: This method overwrites existing `TLSClientConfig`.
func (c *Client) SetTLSClientConfig(config *tls.Config) *Client {
transport, err := c.Transport()
if err != nil {
c.log.Errorf("%v", err)
return c
}
transport.TLSClientConfig = config
return c
}
// SetProxy method sets the Proxy URL and Port for Resty client.
//
// client.SetProxy("http://proxyserver:8888")
//
// OR Without this `SetProxy` method, you could also set Proxy via environment variable.
//
// Refer to godoc `http.ProxyFromEnvironment`.
func (c *Client) SetProxy(proxyURL string) *Client {
transport, err := c.Transport()
if err != nil {
c.log.Errorf("%v", err)
return c
}
pURL, err := url.Parse(proxyURL)
if err != nil {
c.log.Errorf("%v", err)
return c
}
c.proxyURL = pURL
transport.Proxy = http.ProxyURL(c.proxyURL)
return c
}
// RemoveProxy method removes the proxy configuration from Resty client
//
// client.RemoveProxy()
func (c *Client) RemoveProxy() *Client {
transport, err := c.Transport()
if err != nil {
c.log.Errorf("%v", err)
return c
}
c.proxyURL = nil
transport.Proxy = nil
return c
}
// SetCertificates method helps to set client certificates into Resty conveniently.
func (c *Client) SetCertificates(certs ...tls.Certificate) *Client {
config, err := c.tlsConfig()
if err != nil {
c.log.Errorf("%v", err)
return c
}
config.Certificates = append(config.Certificates, certs...)
return c
}
// SetRootCertificate method helps to add one or more root certificates into Resty client
//
// client.SetRootCertificate("/path/to/root/pemFile.pem")
func (c *Client) SetRootCertificate(pemFilePath string) *Client {
rootPemData, err := os.ReadFile(pemFilePath)
if err != nil {
c.log.Errorf("%v", err)
return c
}
config, err := c.tlsConfig()
if err != nil {
c.log.Errorf("%v", err)
return c
}
if config.RootCAs == nil {
config.RootCAs = x509.NewCertPool()
}
config.RootCAs.AppendCertsFromPEM(rootPemData)
return c
}
// SetRootCertificateFromString method helps to add one or more root certificates into Resty client
//
// client.SetRootCertificateFromString("pem file content")
func (c *Client) SetRootCertificateFromString(pemContent string) *Client {
config, err := c.tlsConfig()
if err != nil {
c.log.Errorf("%v", err)
return c
}
if config.RootCAs == nil {
config.RootCAs = x509.NewCertPool()
}
config.RootCAs.AppendCertsFromPEM([]byte(pemContent))
return c
}
// SetOutputDirectory method sets output directory for saving HTTP response into file.
// If the output directory not exists then resty creates one. This setting is optional one,
// if you're planning using absolute path in `Request.SetOutput` and can used together.
//
// client.SetOutputDirectory("/save/http/response/here")
func (c *Client) SetOutputDirectory(dirPath string) *Client {
c.outputDirectory = dirPath
return c
}
// SetRateLimiter sets an optional `RateLimiter`. If set the rate limiter will control
// all requests made with this client.
//
// Since v2.9.0
func (c *Client) SetRateLimiter(rl RateLimiter) *Client {
c.rateLimiter = rl
return c
}
// SetTransport method sets custom `*http.Transport` or any `http.RoundTripper`
// compatible interface implementation in the resty client.
//
// Note:
//
// - If transport is not type of `*http.Transport` then you may not be able to
// take advantage of some of the Resty client settings.
//
// - It overwrites the Resty client transport instance and it's configurations.
//
// transport := &http.Transport{
// // something like Proxying to httptest.Server, etc...
// Proxy: func(req *http.Request) (*url.URL, error) {
// return url.Parse(server.URL)
// },
// }
//
// client.SetTransport(transport)
func (c *Client) SetTransport(transport http.RoundTripper) *Client {
if transport != nil {
c.httpClient.Transport = transport
}
return c
}
// SetScheme method sets custom scheme in the Resty client. It's way to override default.
//
// client.SetScheme("http")
func (c *Client) SetScheme(scheme string) *Client {
if !IsStringEmpty(scheme) {
c.scheme = strings.TrimSpace(scheme)
}
return c
}
// SetCloseConnection method sets variable `Close` in http request struct with the given
// value. More info: https://golang.org/src/net/http/request.go
func (c *Client) SetCloseConnection(close bool) *Client {
c.closeConnection = close
return c
}
// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically.
// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body,
// otherwise you might get into connection leaks, no connection reuse.
//
// Note: Response middlewares are not applicable, if you use this option. Basically you have
// taken over the control of response parsing from `Resty`.
func (c *Client) SetDoNotParseResponse(parse bool) *Client {
c.notParseResponse = parse
return c
}
// SetPathParam method sets single URL path key-value pair in the
// Resty client instance.
//
// client.SetPathParam("userId", "sample@sample.com")
//
// Result:
// URL - /v1/users/{userId}/details
// Composed URL - /v1/users/sample@sample.com/details
//
// It replaces the value of the key while composing the request URL.
// The value will be escaped using `url.PathEscape` function.
//
// Also it can be overridden at request level Path Params options,
// see `Request.SetPathParam` or `Request.SetPathParams`.
func (c *Client) SetPathParam(param, value string) *Client {
c.PathParams[param] = value
return c
}
// SetPathParams method sets multiple URL path key-value pairs at one go in the
// Resty client instance.
//
// client.SetPathParams(map[string]string{
// "userId": "sample@sample.com",
// "subAccountId": "100002",
// "path": "groups/developers",
// })
//
// Result:
// URL - /v1/users/{userId}/{subAccountId}/{path}/details
// Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details
//
// It replaces the value of the key while composing the request URL.
// The values will be escaped using `url.PathEscape` function.
//
// Also it can be overridden at request level Path Params options,
// see `Request.SetPathParam` or `Request.SetPathParams`.
func (c *Client) SetPathParams(params map[string]string) *Client {
for p, v := range params {
c.SetPathParam(p, v)
}
return c
}
// SetRawPathParam method sets single URL path key-value pair in the
// Resty client instance.
//
// client.SetPathParam("userId", "sample@sample.com")
//
// Result:
// URL - /v1/users/{userId}/details
// Composed URL - /v1/users/sample@sample.com/details
//
// client.SetPathParam("path", "groups/developers")
//
// Result:
// URL - /v1/users/{userId}/details
// Composed URL - /v1/users/groups%2Fdevelopers/details
//
// It replaces the value of the key while composing the request URL.
// The value will be used as it is and will not be escaped.
//
// Also it can be overridden at request level Path Params options,
// see `Request.SetPathParam` or `Request.SetPathParams`.
//
// Since v2.8.0
func (c *Client) SetRawPathParam(param, value string) *Client {
c.RawPathParams[param] = value
return c
}
// SetRawPathParams method sets multiple URL path key-value pairs at one go in the
// Resty client instance.
//
// client.SetPathParams(map[string]string{
// "userId": "sample@sample.com",
// "subAccountId": "100002",
// "path": "groups/developers",
// })
//
// Result:
// URL - /v1/users/{userId}/{subAccountId}/{path}/details
// Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details
//
// It replaces the value of the key while composing the request URL.
// The values will be used as they are and will not be escaped.
//
// Also it can be overridden at request level Path Params options,
// see `Request.SetPathParam` or `Request.SetPathParams`.
//
// Since v2.8.0
func (c *Client) SetRawPathParams(params map[string]string) *Client {
for p, v := range params {
c.SetRawPathParam(p, v)
}
return c
}
// SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal.
//
// Note: This option only applicable to standard JSON Marshaller.
func (c *Client) SetJSONEscapeHTML(b bool) *Client {
c.jsonEscapeHTML = b
return c
}
// EnableTrace method enables the Resty client trace for the requests fired from
// the client using `httptrace.ClientTrace` and provides insights.
//
// client := resty.New().EnableTrace()
//
// resp, err := client.R().Get("https://httpbin.org/get")
// fmt.Println("Error:", err)
// fmt.Println("Trace Info:", resp.Request.TraceInfo())
//
// Also `Request.EnableTrace` available too to get trace info for single request.
//
// Since v2.0.0
func (c *Client) EnableTrace() *Client {
c.trace = true
return c
}
// DisableTrace method disables the Resty client trace. Refer to `Client.EnableTrace`.
//
// Since v2.0.0
func (c *Client) DisableTrace() *Client {
c.trace = false
return c
}
// IsProxySet method returns the true is proxy is set from resty client otherwise
// false. By default proxy is set from environment, refer to `http.ProxyFromEnvironment`.
func (c *Client) IsProxySet() bool {
return c.proxyURL != nil
}
// GetClient method returns the current `http.Client` used by the resty client.
func (c *Client) GetClient() *http.Client {
return c.httpClient
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Client Unexported methods
//_______________________________________________________________________
// Executes method executes the given `Request` object and returns response
// error.
func (c *Client) execute(req *Request) (*Response, error) {
// Lock the user-defined pre-request hooks.
c.udBeforeRequestLock.RLock()
defer c.udBeforeRequestLock.RUnlock()
// Lock the post-request hooks.
c.afterResponseLock.RLock()
defer c.afterResponseLock.RUnlock()
// Apply Request middleware
var err error
// user defined on before request methods
// to modify the *resty.Request object
for _, f := range c.udBeforeRequest {
if err = f(c, req); err != nil {
return nil, wrapNoRetryErr(err)
}
}
// If there is a rate limiter set for this client, the Execute call
// will return an error if the rate limit is exceeded.
if req.client.rateLimiter != nil {
if !req.client.rateLimiter.Allow() {
return nil, wrapNoRetryErr(ErrRateLimitExceeded)
}
}
// resty middlewares
for _, f := range c.beforeRequest {
if err = f(c, req); err != nil {
return nil, wrapNoRetryErr(err)
}
}
if hostHeader := req.Header.Get("Host"); hostHeader != "" {
req.RawRequest.Host = hostHeader
}
// call pre-request if defined
if c.preReqHook != nil {
if err = c.preReqHook(c, req.RawRequest); err != nil {
return nil, wrapNoRetryErr(err)
}
}
if err = requestLogger(c, req); err != nil {
return nil, wrapNoRetryErr(err)
}
req.RawRequest.Body = newRequestBodyReleaser(req.RawRequest.Body, req.bodyBuf)
req.Time = time.Now()
resp, err := c.httpClient.Do(req.RawRequest)
response := &Response{
Request: req,
RawResponse: resp,
}
if err != nil || req.notParseResponse || c.notParseResponse {
response.setReceivedAt()
return response, err
}
if !req.isSaveResponse {
defer closeq(resp.Body)
body := resp.Body
// GitHub #142 & #187
if strings.EqualFold(resp.Header.Get(hdrContentEncodingKey), "gzip") && resp.ContentLength != 0 {
if _, ok := body.(*gzip.Reader); !ok {
body, err = gzip.NewReader(body)
if err != nil {
response.setReceivedAt()
return response, err
}
defer closeq(body)
}
}
if response.body, err = io.ReadAll(body); err != nil {
response.setReceivedAt()
return response, err
}
response.size = int64(len(response.body))
}
response.setReceivedAt() // after we read the body
// Apply Response middleware
for _, f := range c.afterResponse {
if err = f(c, response); err != nil {
break
}
}
return response, wrapNoRetryErr(err)
}
// getting TLS client config if not exists then create one
func (c *Client) tlsConfig() (*tls.Config, error) {
transport, err := c.Transport()
if err != nil {
return nil, err
}
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{}
}
return transport.TLSClientConfig, nil
}
// Transport method returns `*http.Transport` currently in use or error
// in case currently used `transport` is not a `*http.Transport`.
//
// Since v2.8.0 become exported method.
func (c *Client) Transport() (*http.Transport, error) {
if transport, ok := c.httpClient.Transport.(*http.Transport); ok {
return transport, nil
}
return nil, errors.New("current transport is not an *http.Transport instance")
}
// just an internal helper method
func (c *Client) outputLogTo(w io.Writer) *Client {
c.log.(*logger).l.SetOutput(w)
return c
}
// ResponseError is a wrapper for including the server response with an error.
// Neither the err nor the response should be nil.
type ResponseError struct {
Response *Response
Err error
}
func (e *ResponseError) Error() string {
return e.Err.Error()
}
func (e *ResponseError) Unwrap() error {
return e.Err
}
// Helper to run errorHooks hooks.
// It wraps the error in a ResponseError if the resp is not nil
// so hooks can access it.
func (c *Client) onErrorHooks(req *Request, resp *Response, err error) {
if err != nil {
if resp != nil { // wrap with ResponseError
err = &ResponseError{Response: resp, Err: err}
}
for _, h := range c.errorHooks {
h(req, err)
}
} else {
for _, h := range c.successHooks {
h(c, resp)
}
}
}
// Helper to run panicHooks hooks.
func (c *Client) onPanicHooks(req *Request, err error) {
for _, h := range c.panicHooks {
h(req, err)
}
}
// Helper to run invalidHooks hooks.
func (c *Client) onInvalidHooks(req *Request, err error) {
for _, h := range c.invalidHooks {
h(req, err)
}
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// File struct and its methods
//_______________________________________________________________________
// File struct represent file information for multipart request
type File struct {
Name string
ParamName string
io.Reader
}
// String returns string value of current file details
func (f *File) String() string {
return fmt.Sprintf("ParamName: %v; FileName: %v", f.ParamName, f.Name)
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// MultipartField struct
//_______________________________________________________________________
// MultipartField struct represent custom data part for multipart request
type MultipartField struct {
Param string
FileName string
ContentType string
io.Reader
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Unexported package methods
//_______________________________________________________________________
func createClient(hc *http.Client) *Client {
if hc.Transport == nil {
hc.Transport = createTransport(nil)
}
c := &Client{ // not setting lang default values
QueryParam: url.Values{},
FormData: url.Values{},
Header: http.Header{},
Cookies: make([]*http.Cookie, 0),
RetryWaitTime: defaultWaitTime,
RetryMaxWaitTime: defaultMaxWaitTime,
PathParams: make(map[string]string),
RawPathParams: make(map[string]string),
JSONMarshal: json.Marshal,
JSONUnmarshal: json.Unmarshal,
XMLMarshal: xml.Marshal,
XMLUnmarshal: xml.Unmarshal,
HeaderAuthorizationKey: http.CanonicalHeaderKey("Authorization"),
jsonEscapeHTML: true,
httpClient: hc,
debugBodySizeLimit: math.MaxInt32,
}
// Logger
c.SetLogger(createLogger())
// default before request middlewares
c.beforeRequest = []RequestMiddleware{
parseRequestURL,
parseRequestHeader,
parseRequestBody,
createHTTPRequest,
addCredentials,
}
// user defined request middlewares
c.udBeforeRequest = []RequestMiddleware{}
// default after response middlewares
c.afterResponse = []ResponseMiddleware{
responseLogger,
parseResponseBody,
saveResponseIntoFile,
}
return c
}
|