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