http_client

package
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 23, 2021 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
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"
)

Variables

This section is empty.

Functions

func Backoff

func Backoff(operation func() (*Response, error), options ...Option) error

Backoff retries with increasing timeout duration up until X amount of retries (Default is 3 attempts, Override with option Retries(n))

func DetectContentType

func DetectContentType(body interface{}) string

DetectContentType method is used to figure out `Request.Body` content type for request header

func IsJSONType

func IsJSONType(ct string) bool

IsJSONType method is to check JSON content type or not

func IsStringEmpty

func IsStringEmpty(str string) bool

func IsXMLType

func IsXMLType(ct string) bool

IsXMLType method is to check XML content type or not

func Unmarshalc

func Unmarshalc(c *HttpClient, ct string, b []byte, d interface{}) (err error)

Unmarshalc content into object from JSON or XML

Types

type ErrorHook

type ErrorHook func(*Request, error)

ErrorHook type is for reacting to request errors, called after all retries were attempted

type File

type File struct {
	Name      string
	ParamName string
	io.Reader
}

func (*File) String

func (f *File) String() string

type HttpClient

type HttpClient struct {
	BaseUrl               string
	QueryParam            url.Values
	FormData              url.Values
	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
	Marshaller            marshallers.Marshaller

	HeaderAuthorizationKey string
	// contains filtered or unexported fields
}

func New

func New() *HttpClient

func NewWithClient

func NewWithClient(hc *http.Client) *HttpClient

func NewWithLocalAddr

func NewWithLocalAddr(localAddr net.Addr) *HttpClient

func (*HttpClient) AddRetryAfterErrorCondition

func (c *HttpClient) AddRetryAfterErrorCondition() *HttpClient

func (*HttpClient) AddRetryCondition

func (c *HttpClient) AddRetryCondition(condition RetryConditionFunc) *HttpClient

func (*HttpClient) AddRetryHook

func (c *HttpClient) AddRetryHook(hook OnRetryFunc) *HttpClient

func (*HttpClient) DisableTrace

func (c *HttpClient) DisableTrace() *HttpClient

func (*HttpClient) EnableTrace

func (c *HttpClient) EnableTrace() *HttpClient

func (*HttpClient) GetClient

func (c *HttpClient) GetClient() *http.Client

func (*HttpClient) IsProxySet

func (c *HttpClient) IsProxySet() bool

func (*HttpClient) NewRequest

func (c *HttpClient) NewRequest() *Request

func (*HttpClient) OnAfterResponse

func (c *HttpClient) OnAfterResponse(m ResponseMiddleware) *HttpClient

func (*HttpClient) OnBeforeRequest

func (c *HttpClient) OnBeforeRequest(m RequestMiddleware) *HttpClient

func (*HttpClient) OnError

func (c *HttpClient) OnError(h ErrorHook) *HttpClient

func (*HttpClient) OnRequestLog

func (c *HttpClient) OnRequestLog(rl RequestLogCallback) *HttpClient

func (*HttpClient) OnResponseLog

func (c *HttpClient) OnResponseLog(rl ResponseLogCallback) *HttpClient

func (*HttpClient) RemoveProxy

func (c *HttpClient) RemoveProxy() *HttpClient

func (*HttpClient) UseAllowGetMethodPayload

func (c *HttpClient) UseAllowGetMethodPayload(a bool) *HttpClient

func (*HttpClient) UseAuthenticationSchema

func (c *HttpClient) UseAuthenticationSchema(scheme string) *HttpClient

func (*HttpClient) UseAuthenticationToken

func (c *HttpClient) UseAuthenticationToken(token string) *HttpClient

func (*HttpClient) UseBaseUrl

func (c *HttpClient) UseBaseUrl(url string) *HttpClient

func (*HttpClient) UseBasicAuthentication

func (c *HttpClient) UseBasicAuthentication(username, password string) *HttpClient

func (*HttpClient) UseCertificates

func (c *HttpClient) UseCertificates(certs ...tls.Certificate) *HttpClient

func (*HttpClient) UseCloseConnection

func (c *HttpClient) UseCloseConnection(close bool) *HttpClient

func (*HttpClient) UseContentLength

func (c *HttpClient) UseContentLength(l bool) *HttpClient

func (*HttpClient) UseCookie

func (c *HttpClient) UseCookie(hc *http.Cookie) *HttpClient

func (*HttpClient) UseCookieJar

func (c *HttpClient) UseCookieJar(jar http.CookieJar) *HttpClient

func (*HttpClient) UseCookies

func (c *HttpClient) UseCookies(cs []*http.Cookie) *HttpClient

func (*HttpClient) UseDebug

func (c *HttpClient) UseDebug(d bool) *HttpClient

func (*HttpClient) UseDebugBodyLimit

func (c *HttpClient) UseDebugBodyLimit(sl int64) *HttpClient

func (*HttpClient) UseDisableWarnings

func (c *HttpClient) UseDisableWarnings(d bool) *HttpClient

func (*HttpClient) UseDoNotParseResponse

func (c *HttpClient) UseDoNotParseResponse(parse bool) *HttpClient

func (*HttpClient) UseError

func (c *HttpClient) UseError(err interface{}) *HttpClient

func (*HttpClient) UseFormData

func (c *HttpClient) UseFormData(data map[string]string) *HttpClient

func (*HttpClient) UseHeader

func (c *HttpClient) UseHeader(header, value string) *HttpClient

func (*HttpClient) UseHeaderVerbatim

func (c *HttpClient) UseHeaderVerbatim(header, value string) *HttpClient

func (*HttpClient) UseHeaders

func (c *HttpClient) UseHeaders(headers map[string]string) *HttpClient

func (*HttpClient) UseJSONEscapeHTML

func (c *HttpClient) UseJSONEscapeHTML(b bool) *HttpClient

func (*HttpClient) UseLogger

func (c *HttpClient) UseLogger(l logger.Logger) *HttpClient

func (*HttpClient) UseOutputDirectory

func (c *HttpClient) UseOutputDirectory(dirPath string) *HttpClient

func (*HttpClient) UsePathParam

func (c *HttpClient) UsePathParam(param, value string) *HttpClient

func (*HttpClient) UsePathParams

func (c *HttpClient) UsePathParams(params map[string]string) *HttpClient

func (*HttpClient) UsePreRequestHook

func (c *HttpClient) UsePreRequestHook(h PreRequestHook) *HttpClient

func (*HttpClient) UseProxy

func (c *HttpClient) UseProxy(proxyURL string) *HttpClient

func (*HttpClient) UseQueryParam

func (c *HttpClient) UseQueryParam(param, value string) *HttpClient

func (*HttpClient) UseQueryParams

func (c *HttpClient) UseQueryParams(params map[string]string) *HttpClient

func (*HttpClient) UseRedirectPolicy

func (c *HttpClient) UseRedirectPolicy(policies ...interface{}) *HttpClient

func (*HttpClient) UseRetryAfter

func (c *HttpClient) UseRetryAfter(callback RetryAfterFunc) *HttpClient

func (*HttpClient) UseRetryCount

func (c *HttpClient) UseRetryCount(count int) *HttpClient

func (*HttpClient) UseRetryMaxWaitTime

func (c *HttpClient) UseRetryMaxWaitTime(maxWaitTime time.Duration) *HttpClient

func (*HttpClient) UseRetryWaitTime

func (c *HttpClient) UseRetryWaitTime(waitTime time.Duration) *HttpClient

func (*HttpClient) UseRootCertificate

func (c *HttpClient) UseRootCertificate(pemFilePath string) *HttpClient

func (*HttpClient) UseRootCertificateFromString

func (c *HttpClient) UseRootCertificateFromString(pemContent string) *HttpClient

func (*HttpClient) UseSchema

func (c *HttpClient) UseSchema(scheme string) *HttpClient

func (*HttpClient) UseTLSClientConfiguration

func (c *HttpClient) UseTLSClientConfiguration(config *tls.Config) *HttpClient

func (*HttpClient) UseTimeout

func (c *HttpClient) UseTimeout(timeout time.Duration) *HttpClient

func (*HttpClient) UseTransport

func (c *HttpClient) UseTransport(transport http.RoundTripper) *HttpClient

type MultipartField

type MultipartField struct {
	Param       string
	FileName    string
	ContentType string
	io.Reader
}

type OnRetryFunc

type OnRetryFunc func(*Response, error)

OnRetryFunc is for side-effecting functions triggered on retry

type Option

type Option func(*Options)

Option is to create convenient retry options like wait time, max retries, etc.

func MaxWaitTime

func MaxWaitTime(value time.Duration) Option

MaxWaitTime sets the max wait time to sleep between requests

func Retries

func Retries(value int) Option

Retries sets the max number of retries

func RetryConditions

func RetryConditions(conditions []RetryConditionFunc) Option

RetryConditions sets the conditions that will be checked for retry.

func RetryHooks

func RetryHooks(hooks []OnRetryFunc) Option

RetryHooks sets the hooks that will be executed after each retry

func WaitTime

func WaitTime(value time.Duration) Option

WaitTime sets the default wait time to sleep between requests

type Options

type Options struct {
	// contains filtered or unexported fields
}

Options struct is used to hold retry settings.

type PreRequestHook

type PreRequestHook func(*HttpClient, *http.Request) error

PreRequestHook type is for the request hook, called right before the request is sent

type RedirectPolicy

type RedirectPolicy interface {
	Apply(req *http.Request, via []*http.Request) error
}

func DomainCheckRedirectPolicy

func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy

func FlexibleRedirectPolicy

func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy

func NoRedirectPolicy

func NoRedirectPolicy() RedirectPolicy

type RedirectPolicyFunc

type RedirectPolicyFunc func(*http.Request, []*http.Request) error

func (RedirectPolicyFunc) Apply

func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error

type Request

type Request struct {
	URL        string
	Method     string
	Token      string
	AuthScheme string
	QueryParam url.Values
	FormData   url.Values
	Header     http.Header
	Time       time.Time
	Body       interface{}
	Result     interface{}
	Error      interface{}
	RawRequest *http.Request
	SRV        *SRVRecord
	UserInfo   *User
	Cookies    []*http.Cookie

	Attempt int
	// contains filtered or unexported fields
}

func (*Request) Context

func (r *Request) Context() context.Context

func (*Request) Delete

func (r *Request) Delete(url string) (*Response, error)

Delete method does DELETE HTTP request. It's defined in section 4.3.5 of RFC7231.

func (*Request) EnableTrace

func (r *Request) EnableTrace() *Request

func (*Request) Execute

func (r *Request) Execute(method, url string) (*Response, error)

func (*Request) ExpectContentType

func (r *Request) ExpectContentType(contentType string) *Request

func (*Request) ForceContentType

func (r *Request) ForceContentType(contentType string) *Request

func (*Request) Get

func (r *Request) Get(url string) (*Response, error)

Get method does GET HTTP request. It's defined in section 4.3.1 of RFC7231.

func (*Request) Head

func (r *Request) Head(url string) (*Response, error)

Head method does HEAD HTTP request. It's defined in section 4.3.2 of RFC7231.

func (*Request) Options

func (r *Request) Options(url string) (*Response, error)

Options method does OPTIONS HTTP request. It's defined in section 4.3.7 of RFC7231.

func (*Request) Patch

func (r *Request) Patch(url string) (*Response, error)

Patch method does PATCH HTTP request. It's defined in section 2 of RFC5789.

func (*Request) Post

func (r *Request) Post(url string) (*Response, error)

Post method does POST HTTP request. It's defined in section 4.3.3 of RFC7231.

func (*Request) Put

func (r *Request) Put(url string) (*Response, error)

Put method does PUT HTTP request. It's defined in section 4.3.4 of RFC7231.

func (*Request) Send

func (r *Request) Send() (*Response, error)

func (*Request) TraceInfo

func (r *Request) TraceInfo() TraceInfo

func (*Request) UseAuthenticationSchema

func (r *Request) UseAuthenticationSchema(scheme string) *Request

func (*Request) UseAuthenticationToken

func (r *Request) UseAuthenticationToken(token string) *Request

func (*Request) UseBasicAuthentication

func (r *Request) UseBasicAuthentication(username, password string) *Request

func (*Request) UseBody

func (r *Request) UseBody(body interface{}) *Request

func (*Request) UseContentLength

func (r *Request) UseContentLength(l bool) *Request

func (*Request) UseContext

func (r *Request) UseContext(ctx context.Context) *Request

func (*Request) UseCookie

func (r *Request) UseCookie(hc *http.Cookie) *Request

func (*Request) UseCookies

func (r *Request) UseCookies(rs []*http.Cookie) *Request

func (*Request) UseDoNotParseResponse

func (r *Request) UseDoNotParseResponse(parse bool) *Request

func (*Request) UseError

func (r *Request) UseError(err interface{}) *Request

func (*Request) UseFile

func (r *Request) UseFile(param, filePath string) *Request

func (*Request) UseFileReader

func (r *Request) UseFileReader(param, fileName string, reader io.Reader) *Request

func (*Request) UseFiles

func (r *Request) UseFiles(files map[string]string) *Request

func (*Request) UseFormData

func (r *Request) UseFormData(data map[string]string) *Request

func (*Request) UseFormDataFromValues

func (r *Request) UseFormDataFromValues(data url.Values) *Request

func (*Request) UseHeader

func (r *Request) UseHeader(header, value string) *Request

func (*Request) UseHeaderVerbatim

func (r *Request) UseHeaderVerbatim(header, value string) *Request

func (*Request) UseHeaders

func (r *Request) UseHeaders(headers map[string]string) *Request

func (*Request) UseJSONEscapeHTML

func (r *Request) UseJSONEscapeHTML(b bool) *Request

func (*Request) UseMultipartField

func (r *Request) UseMultipartField(param, fileName, contentType string, reader io.Reader) *Request

func (*Request) UseMultipartFields

func (r *Request) UseMultipartFields(fields ...*MultipartField) *Request

func (*Request) UseMultipartFormData

func (r *Request) UseMultipartFormData(data map[string]string) *Request

func (*Request) UseOutputFile

func (r *Request) UseOutputFile(file string) *Request

func (*Request) UsePathParam

func (r *Request) UsePathParam(param, value string) *Request

func (*Request) UsePathParams

func (r *Request) UsePathParams(params map[string]string) *Request

func (*Request) UseQueryParam

func (r *Request) UseQueryParam(param, value string) *Request

func (*Request) UseQueryParams

func (r *Request) UseQueryParams(params map[string]string) *Request

func (*Request) UseQueryParamsFromValues

func (r *Request) UseQueryParamsFromValues(params url.Values) *Request

func (*Request) UseQueryString

func (r *Request) UseQueryString(query string) *Request

func (*Request) UseResponse

func (r *Request) UseResponse(res interface{}) *Request

func (*Request) UseSRV

func (r *Request) UseSRV(srv *SRVRecord) *Request

type RequestLog

type RequestLog struct {
	Header http.Header
	Body   string
}

type RequestLogCallback

type RequestLogCallback func(*RequestLog) error

RequestLogCallback type is for request logs, called before the request is logged

type RequestMiddleware

type RequestMiddleware func(*HttpClient, *Request) error

RequestMiddleware type is for request middleware, called before a request is sent

type Response

type Response struct {
	Request     *Request
	RawResponse *http.Response
	// contains filtered or unexported fields
}

func (*Response) CalculateDuration

func (r *Response) CalculateDuration() time.Duration

func (*Response) ExtractBody

func (r *Response) ExtractBody() []byte

func (*Response) ExtractBodyAsString

func (r *Response) ExtractBodyAsString() string

func (*Response) ExtractCookies

func (r *Response) ExtractCookies() []*http.Cookie

func (*Response) ExtractError

func (r *Response) ExtractError() interface{}

func (*Response) ExtractHeader

func (r *Response) ExtractHeader() http.Header

func (*Response) ExtractProto

func (r *Response) ExtractProto() string

func (*Response) ExtractRawBody

func (r *Response) ExtractRawBody() io.ReadCloser

func (*Response) ExtractResult

func (r *Response) ExtractResult() interface{}

func (*Response) ExtractStatus

func (r *Response) ExtractStatus() string

func (*Response) ExtractStatusCode

func (r *Response) ExtractStatusCode() int

func (*Response) IsError

func (r *Response) IsError() bool

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

func (*Response) ReceivedAt

func (r *Response) ReceivedAt() time.Time

func (*Response) Size

func (r *Response) Size() int64

type ResponseError

type ResponseError struct {
	Response *Response
	Err      error
}

func (*ResponseError) Error

func (e *ResponseError) Error() string

func (*ResponseError) Unwrap

func (e *ResponseError) Unwrap() error

type ResponseLog

type ResponseLog struct {
	Header http.Header
	Body   string
}

type ResponseLogCallback

type ResponseLogCallback func(*ResponseLog) error

ResponseLogCallback type is for response logs, called before the response is logged

type ResponseMiddleware

type ResponseMiddleware func(*HttpClient, *Response) error

ResponseMiddleware type is for response middleware, called after a response has been received

type RetryAfterFunc

type RetryAfterFunc func(*HttpClient, *Response) (time.Duration, error)

RetryAfterFunc returns time to wait before retry For example, it can parse HTTP Retry-After header https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html Non-nil error is returned if it is found that request is not retryable (0, nil) is a special result means 'use default algorithm'

type RetryConditionFunc

type RetryConditionFunc func(*Response, error) bool

RetryConditionFunc type is for retry condition function input: non-nil Response OR request execution error

type SRVRecord

type SRVRecord struct {
	Service string
	Domain  string
}

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 client
	// request execution flow, including retry count.
	RequestAttempt int

	// RemoteAddr returns the remote network address.
	RemoteAddr net.Addr
}

type User

type User struct {
	Username, Password string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL