http_client

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2021 License: MIT Imports: 32 Imported by: 0

README

kenobi-http-client

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() (*HttpResponse, 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 `HttpRequest.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(*HttpRequest, 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            interfaces.Marshaller

	HeaderAuthorizationKey string
	// contains filtered or unexported fields
}

func New

func New(logger logging.Logger, marshaller interfaces.Marshaller) (*HttpClient, error)

func NewWithClient

func NewWithClient(logger logging.Logger, marshaller interfaces.Marshaller, hc *http.Client) (*HttpClient, error)

func NewWithLocalAddr

func NewWithLocalAddr(logger logging.Logger, marshaller interfaces.Marshaller, localAddr net.Addr) (*HttpClient, error)

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() *HttpRequest

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 logging.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 HttpRedirectionPolicy

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

func DomainCheckRedirectPolicy

func DomainCheckRedirectPolicy(hostnames ...string) HttpRedirectionPolicy

func FlexibleRedirectPolicy

func FlexibleRedirectPolicy(noOfRedirect int) HttpRedirectionPolicy

func NoRedirectPolicy

func NoRedirectPolicy() HttpRedirectionPolicy

type HttpRedirectionPolicyFunc

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

func (HttpRedirectionPolicyFunc) Apply

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

type HttpRequest

type HttpRequest 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 (*HttpRequest) Context

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

func (*HttpRequest) Delete

func (r *HttpRequest) Delete(url string) (*HttpResponse, error)

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

func (*HttpRequest) EnableTrace

func (r *HttpRequest) EnableTrace() *HttpRequest

func (*HttpRequest) Execute

func (r *HttpRequest) Execute(method, url string) (*HttpResponse, error)

func (*HttpRequest) ExpectContentType

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

func (*HttpRequest) ForceContentType

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

func (*HttpRequest) Get

func (r *HttpRequest) Get(url string) (*HttpResponse, error)

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

func (*HttpRequest) Head

func (r *HttpRequest) Head(url string) (*HttpResponse, error)

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

func (*HttpRequest) Options

func (r *HttpRequest) Options(url string) (*HttpResponse, error)

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

func (*HttpRequest) Patch

func (r *HttpRequest) Patch(url string) (*HttpResponse, error)

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

func (*HttpRequest) Post

func (r *HttpRequest) Post(url string) (*HttpResponse, error)

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

func (*HttpRequest) Put

func (r *HttpRequest) Put(url string) (*HttpResponse, error)

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

func (*HttpRequest) Send

func (r *HttpRequest) Send() (*HttpResponse, error)

func (*HttpRequest) TraceInfo

func (r *HttpRequest) TraceInfo() HttpTracing

func (*HttpRequest) UseAuthenticationSchema

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

func (*HttpRequest) UseAuthenticationToken

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

func (*HttpRequest) UseBasicAuthentication

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

func (*HttpRequest) UseBody

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

func (*HttpRequest) UseContentLength

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

func (*HttpRequest) UseContext

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

func (*HttpRequest) UseCookie

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

func (*HttpRequest) UseCookies

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

func (*HttpRequest) UseDoNotParseResponse

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

func (*HttpRequest) UseError

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

func (*HttpRequest) UseFile

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

func (*HttpRequest) UseFileReader

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

func (*HttpRequest) UseFiles

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

func (*HttpRequest) UseFormData

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

func (*HttpRequest) UseFormDataFromValues

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

func (*HttpRequest) UseHeader

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

func (*HttpRequest) UseHeaderVerbatim

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

func (*HttpRequest) UseHeaders

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

func (*HttpRequest) UseJSONEscapeHTML

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

func (*HttpRequest) UseMultipartField

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

func (*HttpRequest) UseMultipartFields

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

func (*HttpRequest) UseMultipartFormData

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

func (*HttpRequest) UseOutputFile

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

func (*HttpRequest) UsePathParam

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

func (*HttpRequest) UsePathParams

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

func (*HttpRequest) UseQueryParam

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

func (*HttpRequest) UseQueryParams

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

func (*HttpRequest) UseQueryParamsFromValues

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

func (*HttpRequest) UseQueryString

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

func (*HttpRequest) UseResponse

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

func (*HttpRequest) UseSRV

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

type HttpResponse

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

func (*HttpResponse) CalculateDuration

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

func (*HttpResponse) ExtractBody

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

func (*HttpResponse) ExtractBodyAsString

func (r *HttpResponse) ExtractBodyAsString() string

func (*HttpResponse) ExtractCookies

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

func (*HttpResponse) ExtractError

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

func (*HttpResponse) ExtractHeader

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

func (*HttpResponse) ExtractProto

func (r *HttpResponse) ExtractProto() string

func (*HttpResponse) ExtractRawBody

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

func (*HttpResponse) ExtractResult

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

func (*HttpResponse) ExtractStatus

func (r *HttpResponse) ExtractStatus() string

func (*HttpResponse) ExtractStatusCode

func (r *HttpResponse) ExtractStatusCode() int

func (*HttpResponse) IsError

func (r *HttpResponse) IsError() bool

func (*HttpResponse) IsSuccess

func (r *HttpResponse) IsSuccess() bool

func (*HttpResponse) ReceivedAt

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

func (*HttpResponse) Size

func (r *HttpResponse) Size() int64

type HttpTracing

type HttpTracing 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 MultipartField

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

type OnRetryFunc

type OnRetryFunc func(*HttpResponse, 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 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, *HttpRequest) error

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

type ResponseError

type ResponseError struct {
	Response *HttpResponse
	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, *HttpResponse) error

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

type RetryAfterFunc

type RetryAfterFunc func(*HttpClient, *HttpResponse) (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(*HttpResponse, error) bool

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

type SRVRecord

type SRVRecord struct {
	Service string
	Domain  string
}

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