default.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. // Copyright (c) 2015-2019 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
  2. // resty source code and usage is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package resty
  5. import (
  6. "crypto/tls"
  7. "encoding/json"
  8. "io"
  9. "math"
  10. "net/http"
  11. "net/http/cookiejar"
  12. "net/url"
  13. "os"
  14. "time"
  15. "golang.org/x/net/publicsuffix"
  16. )
  17. // DefaultClient of resty
  18. var DefaultClient *Client
  19. // New method creates a new go-resty client.
  20. func New() *Client {
  21. cookieJar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
  22. return createClient(&http.Client{Jar: cookieJar})
  23. }
  24. // NewWithClient method create a new go-resty client with given `http.Client`.
  25. func NewWithClient(hc *http.Client) *Client {
  26. return createClient(hc)
  27. }
  28. // R creates a new resty request object, it is used form a HTTP/RESTful request
  29. // such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS.
  30. func R() *Request {
  31. return DefaultClient.R()
  32. }
  33. // NewRequest is an alias for R(). Creates a new resty request object, it is used form a HTTP/RESTful request
  34. // such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS.
  35. func NewRequest() *Request {
  36. return R()
  37. }
  38. // SetHostURL sets Host URL. See `Client.SetHostURL for more information.
  39. func SetHostURL(url string) *Client {
  40. return DefaultClient.SetHostURL(url)
  41. }
  42. // SetHeader sets single header. See `Client.SetHeader` for more information.
  43. func SetHeader(header, value string) *Client {
  44. return DefaultClient.SetHeader(header, value)
  45. }
  46. // SetHeaders sets multiple headers. See `Client.SetHeaders` for more information.
  47. func SetHeaders(headers map[string]string) *Client {
  48. return DefaultClient.SetHeaders(headers)
  49. }
  50. // SetCookieJar sets custom http.CookieJar. See `Client.SetCookieJar` for more information.
  51. func SetCookieJar(jar http.CookieJar) *Client {
  52. return DefaultClient.SetCookieJar(jar)
  53. }
  54. // SetCookie sets single cookie object. See `Client.SetCookie` for more information.
  55. func SetCookie(hc *http.Cookie) *Client {
  56. return DefaultClient.SetCookie(hc)
  57. }
  58. // SetCookies sets multiple cookie object. See `Client.SetCookies` for more information.
  59. func SetCookies(cs []*http.Cookie) *Client {
  60. return DefaultClient.SetCookies(cs)
  61. }
  62. // SetQueryParam method sets single parameter and its value. See `Client.SetQueryParam` for more information.
  63. func SetQueryParam(param, value string) *Client {
  64. return DefaultClient.SetQueryParam(param, value)
  65. }
  66. // SetQueryParams method sets multiple parameters and its value. See `Client.SetQueryParams` for more information.
  67. func SetQueryParams(params map[string]string) *Client {
  68. return DefaultClient.SetQueryParams(params)
  69. }
  70. // SetFormData method sets Form parameters and its values. See `Client.SetFormData` for more information.
  71. func SetFormData(data map[string]string) *Client {
  72. return DefaultClient.SetFormData(data)
  73. }
  74. // SetBasicAuth method sets the basic authentication header. See `Client.SetBasicAuth` for more information.
  75. func SetBasicAuth(username, password string) *Client {
  76. return DefaultClient.SetBasicAuth(username, password)
  77. }
  78. // SetAuthToken method sets bearer auth token header. See `Client.SetAuthToken` for more information.
  79. func SetAuthToken(token string) *Client {
  80. return DefaultClient.SetAuthToken(token)
  81. }
  82. // OnBeforeRequest method sets request middleware. See `Client.OnBeforeRequest` for more information.
  83. func OnBeforeRequest(m func(*Client, *Request) error) *Client {
  84. return DefaultClient.OnBeforeRequest(m)
  85. }
  86. // OnAfterResponse method sets response middleware. See `Client.OnAfterResponse` for more information.
  87. func OnAfterResponse(m func(*Client, *Response) error) *Client {
  88. return DefaultClient.OnAfterResponse(m)
  89. }
  90. // SetPreRequestHook method sets the pre-request hook. See `Client.SetPreRequestHook` for more information.
  91. func SetPreRequestHook(h func(*Client, *Request) error) *Client {
  92. return DefaultClient.SetPreRequestHook(h)
  93. }
  94. // SetDebug method enables the debug mode. See `Client.SetDebug` for more information.
  95. func SetDebug(d bool) *Client {
  96. return DefaultClient.SetDebug(d)
  97. }
  98. // SetDebugBodyLimit method sets the response body limit for debug mode. See `Client.SetDebugBodyLimit` for more information.
  99. func SetDebugBodyLimit(sl int64) *Client {
  100. return DefaultClient.SetDebugBodyLimit(sl)
  101. }
  102. // SetAllowGetMethodPayload method allows the GET method with payload. See `Client.SetAllowGetMethodPayload` for more information.
  103. func SetAllowGetMethodPayload(a bool) *Client {
  104. return DefaultClient.SetAllowGetMethodPayload(a)
  105. }
  106. // SetRetryCount method sets the retry count. See `Client.SetRetryCount` for more information.
  107. func SetRetryCount(count int) *Client {
  108. return DefaultClient.SetRetryCount(count)
  109. }
  110. // SetRetryWaitTime method sets the retry wait time. See `Client.SetRetryWaitTime` for more information.
  111. func SetRetryWaitTime(waitTime time.Duration) *Client {
  112. return DefaultClient.SetRetryWaitTime(waitTime)
  113. }
  114. // SetRetryMaxWaitTime method sets the retry max wait time. See `Client.SetRetryMaxWaitTime` for more information.
  115. func SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client {
  116. return DefaultClient.SetRetryMaxWaitTime(maxWaitTime)
  117. }
  118. // AddRetryCondition method appends check function for retry. See `Client.AddRetryCondition` for more information.
  119. func AddRetryCondition(condition RetryConditionFunc) *Client {
  120. return DefaultClient.AddRetryCondition(condition)
  121. }
  122. // SetDisableWarn method disables warning comes from `go-resty` client. See `Client.SetDisableWarn` for more information.
  123. func SetDisableWarn(d bool) *Client {
  124. return DefaultClient.SetDisableWarn(d)
  125. }
  126. // SetLogger method sets given writer for logging. See `Client.SetLogger` for more information.
  127. func SetLogger(w io.Writer) *Client {
  128. return DefaultClient.SetLogger(w)
  129. }
  130. // SetContentLength method enables `Content-Length` value. See `Client.SetContentLength` for more information.
  131. func SetContentLength(l bool) *Client {
  132. return DefaultClient.SetContentLength(l)
  133. }
  134. // SetError method is to register the global or client common `Error` object. See `Client.SetError` for more information.
  135. func SetError(err interface{}) *Client {
  136. return DefaultClient.SetError(err)
  137. }
  138. // SetRedirectPolicy method sets the client redirect poilicy. See `Client.SetRedirectPolicy` for more information.
  139. func SetRedirectPolicy(policies ...interface{}) *Client {
  140. return DefaultClient.SetRedirectPolicy(policies...)
  141. }
  142. // SetHTTPMode method sets go-resty mode into HTTP. See `Client.SetMode` for more information.
  143. func SetHTTPMode() *Client {
  144. return DefaultClient.SetHTTPMode()
  145. }
  146. // SetRESTMode method sets go-resty mode into RESTful. See `Client.SetMode` for more information.
  147. func SetRESTMode() *Client {
  148. return DefaultClient.SetRESTMode()
  149. }
  150. // Mode method returns the current client mode. See `Client.Mode` for more information.
  151. func Mode() string {
  152. return DefaultClient.Mode()
  153. }
  154. // SetTLSClientConfig method sets TLSClientConfig for underling client Transport. See `Client.SetTLSClientConfig` for more information.
  155. func SetTLSClientConfig(config *tls.Config) *Client {
  156. return DefaultClient.SetTLSClientConfig(config)
  157. }
  158. // SetTimeout method sets timeout for request. See `Client.SetTimeout` for more information.
  159. func SetTimeout(timeout time.Duration) *Client {
  160. return DefaultClient.SetTimeout(timeout)
  161. }
  162. // SetProxy method sets Proxy for request. See `Client.SetProxy` for more information.
  163. func SetProxy(proxyURL string) *Client {
  164. return DefaultClient.SetProxy(proxyURL)
  165. }
  166. // RemoveProxy method removes the proxy configuration. See `Client.RemoveProxy` for more information.
  167. func RemoveProxy() *Client {
  168. return DefaultClient.RemoveProxy()
  169. }
  170. // SetCertificates method helps to set client certificates into resty conveniently.
  171. // See `Client.SetCertificates` for more information and example.
  172. func SetCertificates(certs ...tls.Certificate) *Client {
  173. return DefaultClient.SetCertificates(certs...)
  174. }
  175. // SetRootCertificate method helps to add one or more root certificates into resty client.
  176. // See `Client.SetRootCertificate` for more information.
  177. func SetRootCertificate(pemFilePath string) *Client {
  178. return DefaultClient.SetRootCertificate(pemFilePath)
  179. }
  180. // SetOutputDirectory method sets output directory. See `Client.SetOutputDirectory` for more information.
  181. func SetOutputDirectory(dirPath string) *Client {
  182. return DefaultClient.SetOutputDirectory(dirPath)
  183. }
  184. // SetTransport method sets custom `*http.Transport` or any `http.RoundTripper`
  185. // compatible interface implementation in the resty client.
  186. // See `Client.SetTransport` for more information.
  187. func SetTransport(transport http.RoundTripper) *Client {
  188. return DefaultClient.SetTransport(transport)
  189. }
  190. // SetScheme method sets custom scheme in the resty client.
  191. // See `Client.SetScheme` for more information.
  192. func SetScheme(scheme string) *Client {
  193. return DefaultClient.SetScheme(scheme)
  194. }
  195. // SetCloseConnection method sets close connection value in the resty client.
  196. // See `Client.SetCloseConnection` for more information.
  197. func SetCloseConnection(close bool) *Client {
  198. return DefaultClient.SetCloseConnection(close)
  199. }
  200. // SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically.
  201. // See `Client.SetDoNotParseResponse` for more information.
  202. func SetDoNotParseResponse(parse bool) *Client {
  203. return DefaultClient.SetDoNotParseResponse(parse)
  204. }
  205. // SetPathParams method sets the Request path parameter key-value pairs. See
  206. // `Client.SetPathParams` for more information.
  207. func SetPathParams(params map[string]string) *Client {
  208. return DefaultClient.SetPathParams(params)
  209. }
  210. // IsProxySet method returns the true if proxy is set on client otherwise false.
  211. // See `Client.IsProxySet` for more information.
  212. func IsProxySet() bool {
  213. return DefaultClient.IsProxySet()
  214. }
  215. // GetClient method returns the current `http.Client` used by the default resty client.
  216. func GetClient() *http.Client {
  217. return DefaultClient.httpClient
  218. }
  219. //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
  220. // Unexported methods
  221. //___________________________________
  222. func createClient(hc *http.Client) *Client {
  223. c := &Client{
  224. HostURL: "",
  225. QueryParam: url.Values{},
  226. FormData: url.Values{},
  227. Header: http.Header{},
  228. UserInfo: nil,
  229. Token: "",
  230. Cookies: make([]*http.Cookie, 0),
  231. Debug: false,
  232. Log: getLogger(os.Stderr),
  233. RetryCount: 0,
  234. RetryWaitTime: defaultWaitTime,
  235. RetryMaxWaitTime: defaultMaxWaitTime,
  236. JSONMarshal: json.Marshal,
  237. JSONUnmarshal: json.Unmarshal,
  238. jsonEscapeHTML: true,
  239. httpClient: hc,
  240. debugBodySizeLimit: math.MaxInt32,
  241. pathParams: make(map[string]string),
  242. }
  243. // Log Prefix
  244. c.SetLogPrefix("RESTY ")
  245. // Default redirect policy
  246. c.SetRedirectPolicy(NoRedirectPolicy())
  247. // default before request middlewares
  248. c.beforeRequest = []func(*Client, *Request) error{
  249. parseRequestURL,
  250. parseRequestHeader,
  251. parseRequestBody,
  252. createHTTPRequest,
  253. addCredentials,
  254. }
  255. // user defined request middlewares
  256. c.udBeforeRequest = []func(*Client, *Request) error{}
  257. // default after response middlewares
  258. c.afterResponse = []func(*Client, *Response) error{
  259. responseLogger,
  260. parseResponseBody,
  261. saveResponseIntoFile,
  262. }
  263. return c
  264. }
  265. func init() {
  266. DefaultClient = New()
  267. }