easyreq

package module
v0.0.0-...-bb05bed Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2023 License: MIT Imports: 30 Imported by: 0

README

easyreq

Make http request easy

Documentation

Index

Constants

View Source
const (
	MethodGet     = "GET"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodDelete  = "DELETE"
	MethodHead    = "HEAD"
	MethodOptions = "OPTIONS"
	MethodPatch   = "PATCH"
)
View Source
const Version = "0.1.0"

Version represents the released version.

Variables

This section is empty.

Functions

func DetectContentType

func DetectContentType(body any) string

func IsEmptyString

func IsEmptyString(str string) bool

func Unmarshalc

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

Types

type Client

type Client struct {
	// Client level setting
	BaseURL string

	QueryParams url.Values
	FormData    url.Values
	PathParams  map[string]string
	Header      http.Header
	UserInfo    *User
	AuthScheme  string
	Token       string
	Cookies     []*http.Cookie

	// HeaderAuthorizationKey is used to set request authorization header prefix.
	HeaderAuthorizationKey string

	// Error is used to return error message when http status code > 399.
	// It can be a pointer or non-pointer because it's going to convert internally by reflection.
	Error reflect.Type

	// Control flag
	Debug                 bool
	DisableWarn           bool
	AllowGetMethodPayload bool

	// Retry strategy
	RetryCount       int
	RetryWaitTime    time.Duration
	RetryMaxWaitTime time.Duration
	RetryConditions  []RetryConditionFunc
	RetryHooks       []OnRetryFunc
	RetryAfter       RetryAfterFunc

	// Http body encode and decode method
	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
}

Client is used to make http request and set client level settings. It provides an options to override request level settings.

func New

func New() *Client

New creates a new client.

func NewClientWithCookieJar

func NewClientWithCookieJar() *Client

NewClientWithCookieJar creates a new client with cookie jar.

func NewWithClient

func NewWithClient(hc *http.Client) *Client

NewWithClient creates a new client with given http.Client.

func NewWithLocalAddr

func NewWithLocalAddr(localAddr net.Addr) *Client

NewWithLocalAddr creates a new client with given Local Address.

func (*Client) AddRetryAfterErrorCondition

func (c *Client) AddRetryAfterErrorCondition() *Client

func (*Client) AddRetryCondition

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

func (*Client) AddRetryHook

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

func (*Client) DisableTrace

func (c *Client) DisableTrace() *Client

func (*Client) EnableTrace

func (c *Client) EnableTrace() *Client

func (*Client) GetHTTPClient

func (c *Client) GetHTTPClient() *http.Client

func (*Client) IsSetProxy

func (c *Client) IsSetProxy() bool

func (*Client) NewRequest

func (c *Client) NewRequest() *Request

func (*Client) OnAfterResponse

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

func (*Client) OnBeforeRequest

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

func (*Client) OnError

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

func (*Client) OnRequestLog

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

func (*Client) OnResponseLog

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

func (*Client) RemoveProxyURL

func (c *Client) RemoveProxyURL() *Client

func (*Client) Req

func (c *Client) Req() *Request

func (*Client) SetAllowGetMethodPayload

func (c *Client) SetAllowGetMethodPayload(a bool) *Client

func (*Client) SetAuthScheme

func (c *Client) SetAuthScheme(authScheme string) *Client

SetAuthScheme method sets the auth scheme type in HTTP request. For Example: Authorization: <auth-scheme-value> <auth-token-value>

func (*Client) SetAuthToken

func (c *Client) SetAuthToken(token string) *Client

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(url string) *Client

func (*Client) SetBasicAuth

func (c *Client) SetBasicAuth(username, password string) *Client

SetBasicAuth method sets the basic authentication header in HTTP request. For example: Authorization: Basic <base64-encoded-value>

func (*Client) SetCertificates

func (c *Client) SetCertificates(certs ...tls.Certificate) *Client

func (*Client) SetCloseConnection

func (c *Client) SetCloseConnection(b bool) *Client

func (*Client) SetContentLength

func (c *Client) SetContentLength(b bool) *Client

func (*Client) SetCookie

func (c *Client) SetCookie(cookie *http.Cookie) *Client

func (*Client) SetCookieJar

func (c *Client) SetCookieJar(jar http.CookieJar) *Client

func (*Client) SetCookies

func (c *Client) SetCookies(cookies []*http.Cookie) *Client

func (*Client) SetDebug

func (c *Client) SetDebug(d bool) *Client

func (*Client) SetDebugBodySizeLimit

func (c *Client) SetDebugBodySizeLimit(size int64) *Client

func (*Client) SetDisableWarn

func (c *Client) SetDisableWarn(d bool) *Client

func (*Client) SetDoNotParseResponse

func (c *Client) SetDoNotParseResponse(b bool) *Client

func (*Client) SetError

func (c *Client) SetError(err any) *Client

func (*Client) SetFormData

func (c *Client) SetFormData(data map[string]string) *Client

func (*Client) SetHeader

func (c *Client) SetHeader(key, value string) *Client

func (*Client) SetHeaderVerbatim

func (c *Client) SetHeaderVerbatim(header, value string) *Client

func (*Client) SetHeaders

func (c *Client) SetHeaders(headers map[string]string) *Client

func (*Client) SetJSONEscapeHTML

func (c *Client) SetJSONEscapeHTML(b bool) *Client

func (*Client) SetLogger

func (c *Client) SetLogger(l Logger) *Client

func (*Client) SetOutputDirectory

func (c *Client) SetOutputDirectory(dir string) *Client

func (*Client) SetPathParam

func (c *Client) SetPathParam(key, value string) *Client

func (*Client) SetPathParams

func (c *Client) SetPathParams(params map[string]string) *Client

func (*Client) SetPreRequestHook

func (c *Client) SetPreRequestHook(h PreRequestHook) *Client

func (*Client) SetProxyURL

func (c *Client) SetProxyURL(proxyURL string) *Client

func (*Client) SetQueryParam

func (c *Client) SetQueryParam(key, value string) *Client

func (*Client) SetQueryParams

func (c *Client) SetQueryParams(params map[string]string) *Client

func (*Client) SetRedirectPolicy

func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client

func (*Client) SetRetryAfter

func (c *Client) SetRetryAfter(callback RetryAfterFunc) *Client

func (*Client) SetRetryCount

func (c *Client) SetRetryCount(count int) *Client

func (*Client) SetRetryMaxWaitTime

func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client

func (*Client) SetRetryWaitTime

func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client

func (*Client) SetRootCertificate

func (c *Client) SetRootCertificate(pemFilePath string) *Client

func (*Client) SetRootCertificateFromString

func (c *Client) SetRootCertificateFromString(pemContent string) *Client

func (*Client) SetScheme

func (c *Client) SetScheme(scheme string) *Client

SetScheme method sets custom scheme in Client.

client.SetScheme("http")

func (*Client) SetTLSClientConfig

func (c *Client) SetTLSClientConfig(config *tls.Config) *Client

func (*Client) SetTimeOut

func (c *Client) SetTimeOut(timeout time.Duration) *Client

func (*Client) SetTransport

func (c *Client) SetTransport(transport http.RoundTripper) *Client

type ErrorHook

type ErrorHook func(*Request, *Response, error)

type File

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

type Logger

type Logger interface {
	Errorf(format string, v ...any)
	Warnf(format string, v ...any)
	Debugf(format string, v ...any)
}

type OnRetryFunc

type OnRetryFunc func(*Response, error)

OnRetryFunc defines business logic in the retry process.

type Option

type Option func(*Options)

func MaxWaitTime

func MaxWaitTime(value time.Duration) Option

func Retries

func Retries(value int) Option

func RetryConditions

func RetryConditions(conditions []RetryConditionFunc) Option

func RetryHooks

func RetryHooks(hooks []OnRetryFunc) Option

func WaitTime

func WaitTime(value time.Duration) Option

type Options

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

type PreRequestHook

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

type RedirectPolicy

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

func DomainCheckRedirectPolicy

func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy

func FlexibleRedirectPolicy

func FlexibleRedirectPolicy(num 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
	AuthScheme  string
	Token       string
	QueryParams url.Values
	FormData    url.Values
	PathParams  map[string]string
	Header      http.Header
	Time        time.Time
	Body        any
	Result      any
	Error       any
	RawRequest  *http.Request
	SRV         *SRVRecord
	UserInfo    *User
	Cookies     []*http.Cookie
	Attempt     int
	// contains filtered or unexported fields
}

func (*Request) AddRetryCondition

func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request

func (*Request) Context

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

func (*Request) Delete

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

func (*Request) DisableTrace

func (r *Request) DisableTrace() *Request

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)

func (*Request) GetTraceInfo

func (r *Request) GetTraceInfo() TraceInfo

func (*Request) Head

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

func (*Request) Options

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

func (*Request) Patch

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

func (*Request) Post

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

func (*Request) Put

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

func (*Request) Send

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

func (*Request) SetAuthScheme

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

func (*Request) SetAuthToken

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

func (*Request) SetBasicAuth

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

func (*Request) SetBody

func (r *Request) SetBody(body any) *Request

func (*Request) SetContentLength

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

func (*Request) SetContext

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

func (*Request) SetCookie

func (r *Request) SetCookie(cookie *http.Cookie) *Request

func (*Request) SetCookies

func (r *Request) SetCookies(cookies []*http.Cookie) *Request

func (*Request) SetDoNotParseResponse

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

func (*Request) SetError

func (r *Request) SetError(err any) *Request

func (*Request) SetFile

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

func (*Request) SetFileReader

func (r *Request) SetFileReader(field, fileName string, reader io.Reader) *Request

func (*Request) SetFiles

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

func (*Request) SetFormData

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

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string) *Request

func (*Request) SetHeaderMultiValues

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

func (*Request) SetHeaderVerbatim

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

func (*Request) SetHeaders

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

func (*Request) SetJSONEscapeHTML

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

func (*Request) SetOutput

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

func (*Request) SetPathParam

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

func (*Request) SetPathParams

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

func (*Request) SetQueryParam

func (r *Request) SetQueryParam(key, value string) *Request

func (*Request) SetQueryParams

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

func (*Request) SetQueryString

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

func (*Request) SetResult

func (r *Request) SetResult(res any) *Request

func (*Request) SetSRV

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

type RequestLog

type RequestLog struct {
	Header http.Header
	Body   string
}

type RequestLogCallback

type RequestLogCallback func(*RequestLog) error

type RequestMiddleware

type RequestMiddleware func(*Client, *Request) error

type Response

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

func Backoff

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

func (*Response) Body

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

func (*Response) Cookies

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

func (*Response) Cost

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

func (*Response) Error

func (r *Response) Error() any

func (*Response) Header

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

func (*Response) IsError

func (r *Response) IsError() bool

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

func (*Response) Proto

func (r *Response) Proto() string

func (*Response) RawBody

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

func (*Response) ReceivedAt

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

func (*Response) Result

func (r *Response) Result() any

func (*Response) Size

func (r *Response) Size() int64

func (*Response) Status

func (r *Response) Status() string

func (*Response) StatusCode

func (r *Response) StatusCode() int

func (*Response) String

func (r *Response) String() string

type ResponseLog

type ResponseLog struct {
	Header http.Header
	Body   string
}

type ResponseLogCallback

type ResponseLogCallback func(*ResponseLog) error

type ResponseMiddleware

type ResponseMiddleware func(*Client, *Response) error

type RetryAfterFunc

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

RetryAfterFunc defines retry strategy, non-nil error returned if request is not retryable. Function result (0, nil) means using default algorithm.

type RetryConditionFunc

type RetryConditionFunc func(*Response, error) bool

RetryConditionFunc defines the conditions that trigger retry.

type SRVRecord

type SRVRecord struct {
	Service string
	Domain  string
}

type TraceInfo

type TraceInfo struct {
	DNSLookupCost       time.Duration
	GetConnCost         time.Duration
	TCPConnectionCost   time.Duration
	TLSHandshakeCost    time.Duration
	ServerProcessCost   time.Duration
	ContentTransferCost time.Duration
	TotalCost           time.Duration
	ConnReused          bool
	ConnWasIdle         bool
	ConnIdleTime        time.Duration
	RequestAttempt      int
	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