Documentation ¶
Index ¶
- Constants
- Variables
- func AnyString(any any) string
- func Base64Decode(str string) (string, error)
- func Base64Encode(str string) string
- func Base64File(path string) (string, error)
- func Base64Reader(reader io.Reader) (string, error)
- func Base64StdEncoding(base64Str string) io.Reader
- func ConnectUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func DefaultHttpClient(localAddr net.Addr) *http.Client
- func DeleteUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func Download(uri, fileName string) error
- func GetUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func HeadUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func HttpBuildQuery(data map[string]any) string
- func IsJSONType(s string) bool
- func IsMatchString(expr string, s string) bool
- func IsStreamType(s string) bool
- func IsXMLType(s string) bool
- func Md5(str string) string
- func Md5File(path string) (string, error)
- func Md5Reader(reader io.Reader) (string, error)
- func NewReadCloser(content []byte, repeatable bool) io.ReadCloser
- func OptionsUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func PatchUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func PostFormUnmarshal(uri string, data url.Values, d any, args ...ArgsFunc) error
- func PostFormWithFilesUnmarshal(uri string, data url.Values, d any, args ...ArgsFunc) errordeprecated
- func PostJsonUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func PostUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func PutUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func RandomMobileUserAgent() string
- func RandomUserAgent() string
- func RequestRoute(route IRoute) error
- func RequestUnmarshal(method, uri string, data, d any, args ...ArgsFunc) error
- func Sha1(str string) string
- func Sha256(str string) string
- func TraceUnmarshal(uri string, data, d any, args ...ArgsFunc) error
- func URIQuery(uri string, query ...url.Values) *url.URL
- func URLDecode(str string) (string, error)
- func URLEncode(str string) string
- func UrlValues(uvs ...url.Values) url.Values
- type ArgsFunc
- func Debug() ArgsFunc
- func SetTLSConfig(tlsConfig *tls.Config) ArgsFunc
- func WithBasicAuth(username, password string) ArgsFunc
- func WithContentType(contentType string) ArgsFunc
- func WithCookie(k, v string) ArgsFunc
- func WithCookies(cookies map[string]string) ArgsFunc
- func WithHeader(header, value string) ArgsFunc
- func WithHeaders(headers map[string]string) ArgsFunc
- func WithProxyUrl(proxyURL string) ArgsFunc
- func WithTLSKeyCrt(crtFile, keyFile string) ArgsFunc
- func WithToken(token string, Type ...string) ArgsFunc
- func WithUserAgent(userAgent string) ArgsFunc
- type CacheInterface
- type Client
- func (c *Client) AsForm() *Client
- func (c *Client) AsJson() *Client
- func (c *Client) AsXml() *Client
- func (c *Client) BrowserMode() *Client
- func (c *Client) Clone() *Client
- func (c *Client) Connect(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) ConnectBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) ConnectD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) ConnectUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) Delete(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) DeleteBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) DeleteD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) DeleteUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) DoRequest(ctx context.Context, method, uri string, body any) (response *Response, err error)
- func (c *Client) DoRequestBytes(ctx context.Context, method string, uri string, data any) ([]byte, error)
- func (c *Client) DoRequestD(ctx context.Context, method string, uri string, data, d any) (response *Response, err error)
- func (c *Client) DoRequestUnmarshal(ctx context.Context, method string, uri string, data, d any) error
- func (c *Client) Download(ctx context.Context, uri, fileName string) error
- func (c *Client) EnableDebug() *Client
- func (c *Client) EnableTrace() *Client
- func (c *Client) Get(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) GetBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) GetD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) GetUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) Head(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) HeadBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) HeadD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) HeadUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) Next(req *http.Request) (*Response, error)
- func (c *Client) OnAfterRequest(callback RequestCallback) *Client
- func (c *Client) OnBeforeRequest(callback ClientCallback) *Client
- func (c *Client) OnError(h ErrorHook) *Client
- func (c *Client) OnPanic(h ErrorHook) *Client
- func (c *Client) OnResponse(callback ResponseCallback) *Client
- func (c *Client) OnSuccess(h SuccessHook) *Client
- func (c *Client) Options(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) OptionsBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) OptionsD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) OptionsUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) Patch(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) PatchBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) PatchD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) PatchUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) Post(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) PostBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) PostD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) PostForm(ctx context.Context, uri string, data url.Values) (*Response, error)
- func (c *Client) PostFormBytes(ctx context.Context, uri string, data url.Values) ([]byte, error)
- func (c *Client) PostFormD(ctx context.Context, uri string, data url.Values, d any) (response *Response, err error)
- func (c *Client) PostFormUnmarshal(ctx context.Context, uri string, data url.Values, d any) error
- func (c *Client) PostFormWithFiles(ctx context.Context, uri string, data url.Values) (*Response, error)deprecated
- func (c *Client) PostFormWithFilesBytes(ctx context.Context, uri string, data url.Values) ([]byte, error)deprecated
- func (c *Client) PostFormWithFilesD(ctx context.Context, uri string, data url.Values, d any) (response *Response, err error)deprecated
- func (c *Client) PostFormWithFilesUnmarshal(ctx context.Context, uri string, data url.Values, d any) errordeprecated
- func (c *Client) PostJson(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) PostJsonBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) PostJsonD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) PostJsonUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) PostUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) Put(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) PutBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) PutD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) PutUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) SetBaseURL(baseUrl string) *Client
- func (c *Client) SetCheckRedirect(fn func(req *http.Request, via []*http.Request) error)
- func (c *Client) SetCookie(cookie Cookie) *Client
- func (c *Client) SetDebug(debug bool) *Client
- func (c *Client) SetHeader(header http.Header) *Client
- func (c *Client) SetHttpClient(client *http.Client) *Client
- func (c *Client) SetJSONMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client
- func (c *Client) SetJSONUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client
- func (c *Client) SetLogger(logger LoggerInterface) *Client
- func (c *Client) SetQuery(query url.Values) *Client
- func (c *Client) SetRetry(retryCount int, retryWaitTime time.Duration) *Client
- func (c *Client) SetTLSConfig(tlsConfig *tls.Config) *Client
- func (c *Client) SetTimeout(t time.Duration) *Client
- func (c *Client) SetWriter(writer io.Writer) *Client
- func (c *Client) SetXMLMarshaler(marshaler func(v any) ([]byte, error)) *Client
- func (c *Client) SetXMLUnmarshaler(unmarshaler func(data []byte, v any) error) *Client
- func (c *Client) Trace(ctx context.Context, uri string, data any) (*Response, error)
- func (c *Client) TraceBytes(ctx context.Context, uri string, data any) ([]byte, error)
- func (c *Client) TraceD(ctx context.Context, uri string, data, d any) (response *Response, err error)
- func (c *Client) TraceUnmarshal(ctx context.Context, uri string, data, d any) error
- func (c *Client) Unmarshal(contentType string, b []byte, d any) (err error)
- func (c *Client) Use(middlewares ...MiddlewareFunc) *Client
- func (c *Client) WithBasicAuth(username, password string) *Client
- func (c *Client) WithClientJar(jar http.CookieJar) *Client
- func (c *Client) WithContentType(contentType string) *Client
- func (c *Client) WithCookie(k, v string) *Client
- func (c *Client) WithCookieMap(cookies map[string]string) *Client
- func (c *Client) WithCookieNextRequest(cache CacheInterface, ttl time.Duration) *Client
- func (c *Client) WithCookieString(cookieString string) *Client
- func (c *Client) WithHeader(k, v string) *Client
- func (c *Client) WithHeaderKV(callback KVCallback) *Client
- func (c *Client) WithHeaderMap(headers map[string]string) *Client
- func (c *Client) WithHeaderVerbatim(k, v string) *Client
- func (c *Client) WithProxyUrl(proxyURL string) *Client
- func (c *Client) WithQueryKV(callback KVCallback) *Client
- func (c *Client) WithRandomMobileUserAgent() *Client
- func (c *Client) WithRandomUserAgent() *Client
- func (c *Client) WithRedirectLimit(redirectLimit int) *Client
- func (c *Client) WithRedirectPolicy(policies ...any) *Client
- func (c *Client) WithTLSKeyCrt(crtFile, keyFile string) *Client
- func (c *Client) WithToken(token string, authorizationType ...string) *Client
- func (c *Client) WithUserAgent(userAgent string) *Client
- type ClientCallback
- type Cookie
- type CtxKeyString
- type Downloader
- type ErrorHook
- type FileCache
- type IRoute
- type KVCallback
- type Logger
- type LoggerInterface
- type MiddlewareFunc
- type ReadCloser
- type RedirectPolicy
- type RedirectPolicyFunc
- type RequestCallback
- type RequestError
- type Response
- func Connect(uri string, data any, args ...ArgsFunc) (*Response, error)
- func ConnectD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func Delete(uri string, data any, args ...ArgsFunc) (*Response, error)
- func DeleteD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func Get(uri string, data any, args ...ArgsFunc) (*Response, error)
- func GetD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func Head(uri string, data any, args ...ArgsFunc) (*Response, error)
- func HeadD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func Options(uri string, data any, args ...ArgsFunc) (*Response, error)
- func OptionsD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func Patch(uri string, data any, args ...ArgsFunc) (*Response, error)
- func PatchD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func Post(uri string, data any, args ...ArgsFunc) (*Response, error)
- func PostD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func PostForm(uri string, data url.Values, args ...ArgsFunc) (*Response, error)
- func PostFormD(uri string, data url.Values, d any, args ...ArgsFunc) (*Response, error)
- func PostFormWithFiles(uri string, data url.Values, args ...ArgsFunc) (*Response, error)deprecated
- func PostJson(uri string, data any, args ...ArgsFunc) (*Response, error)
- func PostJsonD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func Put(uri string, data any, args ...ArgsFunc) (*Response, error)
- func PutD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func Request(method, uri string, data any, args ...ArgsFunc) (*Response, error)
- func RequestD(method, uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func Trace(uri string, data any, args ...ArgsFunc) (*Response, error)
- func TraceD(uri string, data, d any, args ...ArgsFunc) (*Response, error)
- func (r *Response) Close() error
- func (r *Response) ContentType() string
- func (r *Response) GetCookie() Cookie
- func (r *Response) IsError() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) ReadAll() []byte
- func (r *Response) ReadAllString() string
- func (r *Response) ReadStream(lineNumberFun func(line []byte, number int64)) int64
- func (r *Response) TraceInfo() TraceInfo
- func (r *Response) Unmarshal(d any) error
- type ResponseCallback
- type ResponseError
- type Route
- type SuccessHook
- type TraceInfo
Constants ¶
const ( HttpSchemeName = `http` HttpParamFileHolder = `@file:` HttpRegexParamJson = `^[\w\[\]]+=.+` HttpHeaderHost = `Host` HttpHeaderCookie = `Cookie` HttpHeaderUserAgent = `User-Agent` HttpHeaderAcceptRanges = `Accept-Ranges` HttpHeaderAuthorization = "Authorization" HttpHeaderAccept = "Accept" HttpMIMEEventStream = "text/event-stream" HttpHeaderCacheControl = "Cache-Control" HttpHeaderConnection = "Connection" HttpHeaderContentType = `Content-Type` HttpHeaderContentLength = `Content-Length` CharsetUTF8 = "charset=UTF-8" HttpHeaderContentTypeJson = `application/json` HttpHeaderContentTypeJsonCharsetUTF8 = HttpHeaderContentTypeJson + "; " + CharsetUTF8 HttpHeaderContentTypeXml = `application/xml` HttpHeaderContentTypeXmlCharsetUTF8 = HttpHeaderContentTypeXml + "; " + CharsetUTF8 HttpHeaderContentTypeForm = `application/x-www-form-urlencoded` AuthorizationTypeBearer = "Bearer " AuthorizationTypeBasic = "Basic " )
Variables ¶
var ( ErrDownloaderFileIncomplete = errors.New("incomplete file") ErrDownloaderPartLength = errors.New("the length of the segmented download is incorrect") )
var (
ErrAutoRedirectDisabled = errors.New("auto redirect is disabled")
)
Functions ¶
func AnyString ¶ added in v0.0.15
AnyString converts `any` to string. It's most commonly used converting function.
func Base64Decode ¶ added in v0.0.2
func Base64Encode ¶ added in v0.0.2
func Base64File ¶ added in v0.0.2
func Base64StdEncoding ¶ added in v0.0.4
func ConnectUnmarshal ¶ added in v0.0.6
func DefaultHttpClient ¶ added in v0.0.7
DefaultHttpClient set InsecureSkipVerify = false c.Client.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = false
func DeleteUnmarshal ¶ added in v0.0.6
func GetUnmarshal ¶ added in v0.0.6
func HeadUnmarshal ¶ added in v0.0.6
func HttpBuildQuery ¶
HttpBuildQuery Generate get request parameters
func IsJSONType ¶
IsJSONType method is to check JSON content type or not
func IsMatchString ¶
func IsStreamType ¶ added in v0.0.9
func Md5Reader ¶ added in v0.0.2
Md5Reader f, _ := os.Open("./_example/1.jpeg") f.Seek(0, 0) requests.Md5Reader(f)
func NewReadCloser ¶
func NewReadCloser(content []byte, repeatable bool) io.ReadCloser
NewReadCloser creates and returns a RepeatReadCloser object.
func OptionsUnmarshal ¶ added in v0.0.6
func PatchUnmarshal ¶ added in v0.0.6
func PostFormUnmarshal ¶ added in v0.0.6
func PostJsonUnmarshal ¶ added in v0.0.6
func PostUnmarshal ¶ added in v0.0.6
func PutUnmarshal ¶ added in v0.0.6
func RandomMobileUserAgent ¶ added in v0.0.14
func RandomMobileUserAgent() string
RandomMobileUserAgent generates a random MOBILE browser user-agent on every requests
func RandomUserAgent ¶ added in v0.0.14
func RandomUserAgent() string
RandomUserAgent generates a random DESKTOP browser user-agent on every requests
func RequestRoute ¶ added in v0.0.6
RequestRoute
route := &requests.Route{ Uri: "https://api.github.com/users/github", Method: http.MethodGet, D: &.tests.GitHubUser{}, } _ = requests.RequestRoute(route) fmt.Println(route.GetD().(*.tests.GitHubUser))
func RequestUnmarshal ¶ added in v0.0.6
func TraceUnmarshal ¶ added in v0.0.6
Types ¶
type ArgsFunc ¶ added in v0.0.3
type ArgsFunc func(client *Client)
func SetTLSConfig ¶ added in v0.0.3
func WithBasicAuth ¶ added in v0.0.3
func WithContentType ¶ added in v0.0.3
func WithCookie ¶ added in v0.0.3
func WithCookies ¶ added in v0.0.3
func WithHeader ¶ added in v0.0.3
func WithHeaders ¶ added in v0.0.3
func WithProxyUrl ¶ added in v0.0.3
func WithTLSKeyCrt ¶ added in v0.0.3
func WithUserAgent ¶ added in v0.0.3
type CacheInterface ¶ added in v0.0.18
type CacheInterface interface { Set(key, value string, ttl time.Duration) error Get(key string) (string, error) Has(key string) bool Delete(key string) error CleanExpired() error }
func NewFileCache ¶ added in v0.0.8
func NewFileCache(paths ...string) CacheInterface
NewFileCache
go func() { ticker := time.NewTicker(time.Minute * 5) for range ticker.C { cache.CleanExpired() } }()
type Client ¶
type Client struct { *http.Client Debug bool BaseUrl string Query url.Values QueryKVs []KVCallback Header http.Header HeaderKVs []KVCallback Cookie Cookie Logger LoggerInterface JSONMarshal func(v any) ([]byte, error) JSONUnmarshal func(data []byte, v any) error XMLMarshal func(v any) ([]byte, error) XMLUnmarshal func(data []byte, v any) error // contains filtered or unexported fields }
func NewWithHttpClient ¶ added in v0.0.17
func (*Client) AsForm ¶
AsForm is a chaining function, which sets the HTTP content type as "application/x-www-form-urlencoded" for the next request.
func (*Client) AsJson ¶
AsJson is a chaining function, which sets the HTTP content type as "application/json" for the next request.
Note that it also checks and encodes the parameter to JSON format automatically.
func (*Client) AsXml ¶
AsXml is a chaining function, which sets the HTTP content type as "application/xml" for the next request.
Note that it also checks and encodes the parameter to XML format automatically.
func (*Client) BrowserMode ¶
BrowserMode enables browser mode of the client. When browser mode is enabled, it automatically saves and sends cookie content from and to server.
func (*Client) Connect ¶
Connect send CONNECT request and returns the response object. Note that the response object MUST be closed if it'll never be used.
func (*Client) ConnectBytes ¶ added in v0.0.7
func (*Client) ConnectUnmarshal ¶ added in v0.0.16
func (*Client) Delete ¶
Delete send DELETE request and returns the response object. Note that the response object MUST be closed if it'll never be used.
func (*Client) DeleteBytes ¶ added in v0.0.7
func (*Client) DeleteUnmarshal ¶ added in v0.0.16
func (*Client) DoRequestBytes ¶ added in v0.0.7
func (*Client) DoRequestD ¶ added in v0.0.7
func (*Client) DoRequestUnmarshal ¶ added in v0.0.16
func (*Client) EnableDebug ¶ added in v0.0.18
func (*Client) EnableTrace ¶
func (*Client) Get ¶
Get send GET request and returns the response object. Note that the response object MUST be closed if it'll never be used.
func (*Client) GetUnmarshal ¶ added in v0.0.16
func (*Client) Head ¶
Head send HEAD request and returns the response object. Note that the response object MUST be closed if it'll never be used.
func (*Client) HeadUnmarshal ¶ added in v0.0.16
func (*Client) OnAfterRequest ¶
func (c *Client) OnAfterRequest(callback RequestCallback) *Client
OnAfterRequest method appends request callback into the before request chain.
client.OnAfterRequest(func(client *requests.Client, request *http.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 (*Client) OnBeforeRequest ¶
func (c *Client) OnBeforeRequest(callback ClientCallback) *Client
OnBeforeRequest method appends request callback into the before request chain.
client.OnBeforeRequest(func(c *requests.Client) 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 (*Client) OnError ¶
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(*http.Request, error){ if v, ok := err.(*requests.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 comletes.
func (*Client) OnPanic ¶
OnPanic method adds a callback that will be run whever 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.
func (*Client) OnResponse ¶
func (c *Client) OnResponse(callback ResponseCallback) *Client
OnResponse method appends response callback into the after response chain.
client.OnResponse(func(request *http.Request, response *requests.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 (*Client) OnSuccess ¶
func (c *Client) OnSuccess(h SuccessHook) *Client
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 comletes.
func (*Client) Options ¶
Options send OPTIONS request and returns the response object. Note that the response object MUST be closed if it'll never be used.
func (*Client) OptionsBytes ¶ added in v0.0.7
func (*Client) OptionsUnmarshal ¶ added in v0.0.16
func (*Client) Patch ¶
Patch send PATCH request and returns the response object. Note that the response object MUST be closed if it'll never be used.
func (*Client) PatchBytes ¶ added in v0.0.7
func (*Client) PatchUnmarshal ¶ added in v0.0.16
func (*Client) Post ¶
Post sends request using HTTP method POST and returns the response object. Note that the response object MUST be closed if it'll never be used.
func (*Client) PostForm ¶
PostForm is different from net/http.PostForm. It's a wrapper of Post method, which sets the Content-Type as "multipart/form-data;". and It will automatically set boundary characters for the request body and Content-Type.
It's Seem like the following case:
Content-Type: multipart/form-data; boundary=----Boundarye4Ghaog6giyQ9ncN
And form data is like: ------Boundarye4Ghaog6giyQ9ncN Content-Disposition: form-data; name="checkType"
none
It's used for sending form data. Note that the response object MUST be closed if it'll never be used.
func (*Client) PostFormBytes ¶ added in v0.0.7
func (*Client) PostFormUnmarshal ¶ added in v0.0.16
func (*Client) PostJsonBytes ¶ added in v0.0.7
func (*Client) PostJsonUnmarshal ¶ added in v0.0.16
func (*Client) PostUnmarshal ¶ added in v0.0.16
func (*Client) Put ¶
Put send PUT request and returns the response object. Note that the response object MUST be closed if it'll never be used.
func (*Client) PutUnmarshal ¶ added in v0.0.16
func (*Client) SetBaseURL ¶ added in v0.0.7
func (*Client) SetCheckRedirect ¶ added in v0.0.17
func (*Client) SetHttpClient ¶ added in v0.0.17
func (*Client) SetJSONMarshaler ¶
SetJSONMarshaler method sets the JSON marshaler function to marshal the request body. By default, uses `encoding/json` package to marshal the request body.
func (*Client) SetJSONUnmarshaler ¶
SetJSONUnmarshaler method sets the JSON unmarshaler function to unmarshal the response body.
func (*Client) SetLogger ¶ added in v0.0.18
func (c *Client) SetLogger(logger LoggerInterface) *Client
func (*Client) SetRetry ¶
SetRetry is a chaining function, which sets retry count and interval when failure for next request.
func (*Client) SetTLSConfig ¶
SetTLSConfig sets the TLS configuration of client.
func (*Client) SetTimeout ¶ added in v0.0.17
SetTimeout sets the request timeout for the client.
func (*Client) SetXMLMarshaler ¶
SetXMLMarshaler method sets the XML marshaler function to marshal the request body.
func (*Client) SetXMLUnmarshaler ¶
SetXMLUnmarshaler method sets the XML unmarshaler function to unmarshal the response body. By default, uses `encoding/xml` package to unmarshal the response body.
func (*Client) Trace ¶
Trace send TRACE request and returns the response object. Note that the response object MUST be closed if it'll never be used.
func (*Client) TraceBytes ¶ added in v0.0.7
func (*Client) TraceUnmarshal ¶ added in v0.0.16
func (*Client) Use ¶
func (c *Client) Use(middlewares ...MiddlewareFunc) *Client
Use adds one or more middleware handlers to client.
func (*Client) WithBasicAuth ¶
WithBasicAuth Specify the basic authentication username and password for the request.
func (*Client) WithClientJar ¶ added in v0.0.18
WithClientJar exp: jar, _ := cookiejar.New(nil) WithClientCookieJar(jar)
func (*Client) WithContentType ¶
WithContentType is a chaining function, which sets HTTP content type for the next request.
func (*Client) WithCookie ¶
func (*Client) WithCookieMap ¶ added in v0.0.15
func (*Client) WithCookieNextRequest ¶ added in v0.0.14
func (c *Client) WithCookieNextRequest(cache CacheInterface, ttl time.Duration) *Client
WithCookieNextRequest
The first access to the root domain name will cache cookie data, and the second access will carry the cookie data from the cache until the cache expires and is regenerated cache := requests.NewFileCache("you path/cache") WithCookieNextRequest(cache, time.Hour)
func (*Client) WithCookieString ¶
func (*Client) WithHeader ¶
WithHeader 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.
WithHeader("Content-Type", "application/json"). WithHeader("Accept", "application/json")
func (*Client) WithHeaderKV ¶ added in v0.2.1
func (c *Client) WithHeaderKV(callback KVCallback) *Client
func (*Client) WithHeaderMap ¶ added in v0.0.17
WithHeaderMap 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. For Example: To set `Content-Type` and `Accept` as `application/json`
WithHeaders(map[string]string{ "Content-Type": "application/json", "Accept": "application/json", })
func (*Client) WithHeaderVerbatim ¶
WithHeaderVerbatim 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`.
WithHeaderVerbatim("all_lowercase", "available"). WithHeaderVerbatim("UPPERCASE", "available")
Also you can override header value, which was set at client instance level.
func (*Client) WithProxyUrl ¶
WithProxyUrl set proxy for the client. This func will do nothing when the parameter `proxyURL` is empty or in wrong pattern. The correct pattern is like `http://USER:PASSWORD@IP:PORT` or `socks5://USER:PASSWORD@IP:PORT`. Only `http` and `socks5` proxies are supported currently.
func (*Client) WithQueryKV ¶ added in v0.2.1
func (c *Client) WithQueryKV(callback KVCallback) *Client
func (*Client) WithRandomMobileUserAgent ¶ added in v0.0.14
func (*Client) WithRandomUserAgent ¶ added in v0.0.14
func (*Client) WithRedirectLimit ¶
WithRedirectLimit limits the number of jumps.
func (*Client) WithRedirectPolicy ¶
WithRedirectPolicy method sets the client redirect poilicy. provides ready to use redirect policies. Wanna create one for yourself refer to `redirect.go`.
WithRedirectLimit(20) WithRedirectPolicy(FlexibleRedirectPolicy(20)) WithRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net"))
func (*Client) WithTLSKeyCrt ¶
WithTLSKeyCrt sets the certificate and key file for TLS configuration of client.
func (*Client) WithUserAgent ¶
type ClientCallback ¶ added in v0.0.14
type Cookie ¶ added in v0.0.13
func CookieStringEscape ¶ added in v0.0.15
type CtxKeyString ¶ added in v0.0.18
type CtxKeyString string
type Downloader ¶ added in v0.2.2
type Downloader struct { // 下载源链接 URL string // 下载完成文件名 FileName string //协程数量 CoroutineNumber int // contains filtered or unexported fields }
func NewDownloader ¶ added in v0.2.2
func (*Downloader) Download ¶ added in v0.2.2
func (d *Downloader) Download() error
type FileCache ¶ added in v0.0.8
type FileCache struct {
// contains filtered or unexported fields
}
func (*FileCache) CleanExpired ¶ added in v0.0.8
type KVCallback ¶ added in v0.2.1
type KVCallback func() (k, v string)
type Logger ¶ added in v0.0.14
type Logger struct {
// contains filtered or unexported fields
}
func DefaultLogger ¶ added in v0.0.14
func DefaultLogger() *Logger
type LoggerInterface ¶ added in v0.0.18
type MiddlewareFunc ¶
MiddlewareFunc middleware handler func
type ReadCloser ¶
type ReadCloser struct {
// contains filtered or unexported fields
}
ReadCloser implements the io.ReadCloser interface which is used for reading request body content multiple times.
Note that it cannot be closed.
func (*ReadCloser) Close ¶
func (b *ReadCloser) Close() error
Close implements the io.ReadCloser interface.
type RedirectPolicy ¶
RedirectPolicy to regulate the redirects in the client. Objects implementing the RedirectPolicy interface can be registered as
Apply function should return nil to continue the redirect jounery, otherwise return error to stop the redirect.
func DomainCheckRedirectPolicy ¶
func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy
DomainCheckRedirectPolicy is convenient method to define domain name redirect rule in client. Redirect is allowed for only mentioned host in the policy.
requests.WithRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net"))
func FlexibleRedirectPolicy ¶
func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy
FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client.
func NoRedirectPolicy ¶
func NoRedirectPolicy() RedirectPolicy
NoRedirectPolicy is used to disable redirects in the HTTP client
requests.WithRedirectPolicy(NoRedirectPolicy())
type RedirectPolicyFunc ¶
The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy. If f is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls f.
type RequestCallback ¶ added in v0.0.14
type RequestError ¶ added in v0.0.20
func (*RequestError) Error ¶ added in v0.0.20
func (r *RequestError) Error() string
type Response ¶
type Response struct { *http.Response // Response is the underlying http.Response object of certain request. // contains filtered or unexported fields }
func (*Response) ContentType ¶
ContentType response header Content-Type
func (*Response) IsError ¶
IsError method returns true if HTTP status `code >= 400` otherwise false.
func (*Response) IsSuccess ¶
IsSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false.
func (*Response) ReadAllString ¶
ReadAllString retrieves and returns the response content as string.
func (*Response) ReadStream ¶ added in v0.0.5
ReadStream Microsoft ChatGPT Data Structure start data: {"id":"","object":"","created":0,"model":"","prompt_filter_results":[{"prompt_index":0,"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"choices":[],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"role":"assistant"},"content_filter_results":{}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"我"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"是"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"一个"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"AI"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"助"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"手"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":","},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"可以"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"帮"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"助"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"您"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"查"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"找"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"信息"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"。"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":"stop","delta":{},"content_filter_results":{}}],"usage":null} data: [DONE] Microsoft ChatGPT Data Structure end
type ResponseCallback ¶ added in v0.0.14
type ResponseError ¶
func (*ResponseError) Error ¶
func (e *ResponseError) Error() string
type Route ¶ added in v0.0.6
type Route struct {
Method, Uri string
Header, Cookies map[string]string
TlsConfig *tls.Config
Body, D any
}
func (*Route) GetCookies ¶ added in v0.0.6
func (*Route) GetTlsConfig ¶ added in v0.0.6
type SuccessHook ¶
type TraceInfo ¶
type TraceInfo struct { // DNSLookup is a duration that transport took to perform // DNS lookup. DNSLookup time.Duration // ConnTime is a duration that took to obtain a successful connection. ConnTime time.Duration // TCPConnTime is a duration that took to obtain the TCP connection. TCPConnTime time.Duration // TLSHandshake is a duration that TLS handshake took place. TLSHandshake time.Duration // ServerTime is a duration that server took to respond first byte. ServerTime time.Duration // ResponseTime is a duration since first response byte from server to // request completion. ResponseTime time.Duration // TotalTime is a duration that total request took end-to-end. TotalTime time.Duration // IsConnReused is whether this connection has been previously // used for another HTTP request. IsConnReused bool // IsConnWasIdle is whether this connection was obtained from an // idle pool. IsConnWasIdle bool // ConnIdleTime is a duration how long the connection was previously // idle, if IsConnWasIdle is true. ConnIdleTime time.Duration // RequestAttempt is to represent the request attempt made during a // request execution flow, including retry count. RequestAttempt int // RemoteAddr returns the remote network address. RemoteAddr net.Addr }
Source Files ¶
- cache.go
- callback_cookie.go
- callback_debug.go
- client.go
- client_callback.go
- client_cookie.go
- client_header.go
- client_middleware.go
- client_redirect.go
- client_request.go
- client_request_bytes.go
- client_request_d.go
- client_request_do.go
- client_request_unmarshal.go
- client_trace.go
- cookie.go
- crypto.go
- deprecated_0.3.go
- downloader.go
- errors.go
- interface.go
- logger.go
- random_user_agent.go
- read_closer.go
- request_fun.go
- request_route.go
- response.go
- util.go