Documentation
¶
Overview ¶
standard net/http client library and exposes nearly the same public API. This makes mocking http response very easy to drop into existing programs.
mockhttp performs mock if enabled. Inspired by retryablehttp by hashicorp.
Index ¶
- Variables
- func ReusableReader(r io.Reader) io.Reader
- type Client
- func (c *Client) Do(req *Request) (*http.Response, error)
- func (c *Client) Get(url string) (*http.Response, error)
- func (c *Client) Head(url string) (*http.Response, error)
- func (c *Client) Post(url, contentType string, body interface{}) (*http.Response, error)
- func (c *Client) PostForm(url string, data url.Values) (*http.Response, error)
- func (c *Client) StandardClient() *http.Client
- type LenReader
- type LeveledLogger
- type Logger
- type ReaderFunc
- type Request
- type RequestLogHook
- type ResolverAdapter
- type ResponseHandlerFunc
- type ResponseLogHook
Constants ¶
This section is empty.
Variables ¶
var ( ErrPolicyLoaded = fmt.Errorf("policy loaded") ErrClientMissing = fmt.Errorf("client missing") ErrNoMockResponse = fmt.Errorf("no mock response prepared") ErrUnsupportedContentType = fmt.Errorf("unsupported content type") ErrCommon = fmt.Errorf("common error") ErrNoContentType = fmt.Errorf("unable to find content type") )
Functions ¶
Types ¶
type Client ¶
type Client struct {
HTTPClient *http.Client // Internal HTTP client.
Logger interface{} // Customer logger instance. Can be either Logger or LeveledLogger
// RequestLogHook allows a user-supplied function to be called
// before each httprequest call.
RequestLogHook RequestLogHook
// ResponseLogHook allows a user-supplied function to be called
// with the response from each HTTP request executed.
ResponseLogHook ResponseLogHook
// MockStore represents the datastore.
// The built-in library provides file-based datastore, but it can be easily extended.
Resolver ResolverAdapter
// contains filtered or unexported fields
}
Client is used to make HTTP requests. It adds additional functionality like automatic retries to tolerate minor outages.
func NewClient ¶
func NewClient(resolver ResolverAdapter) *Client
NewClient creates a new Client with default settings.
func (*Client) Do ¶
Do wraps calling an HTTP method with mock possibility. WARN: DON'T USE IT ON PRODUCTION!
func (*Client) PostForm ¶
PostForm is a convenience method for doing simple POST operations using pre-filled url.Values form data.
func (*Client) StandardClient ¶
StandardClient returns a stdlib *http.Client with a custom Transport, which shims in a *mockhttp.Client for added retries.
type LenReader ¶
type LenReader interface {
Len() int
}
LenReader is an interface implemented by many in-memory io.Reader's. Used for automatically sending the right Content-Length header when possible.
type LeveledLogger ¶
type LeveledLogger interface {
Error(msg string, keysAndValues ...interface{})
Info(msg string, keysAndValues ...interface{})
Debug(msg string, keysAndValues ...interface{})
Warn(msg string, keysAndValues ...interface{})
}
LeveledLogger is an interface that can be implemented by any logger or a logger wrapper to provide leveled logging. The methods accept a message string and a variadic number of key-value pairs. For log.Printf style formatting where message string contains a format specifier, use Logger interface.
type Logger ¶
type Logger interface {
Printf(string, ...interface{})
}
Logger interface allows to use other loggers than standard log.Logger.
type ReaderFunc ¶
ReaderFunc is the type of function that can be given natively to NewRequest
type Request ¶
type Request struct {
// Embed an HTTP request directly. This makes a *Request act exactly
// like an *http.Request so that all meta methods are supported.
*http.Request
// contains filtered or unexported fields
}
Request wraps the metadata needed to create HTTP requests.
func FromRequest ¶
FromRequest wraps an http.Request in a retryablehttp.Request
func NewRequest ¶
NewRequest creates a new wrapped request.
func NewRequestWithContext ¶
func NewRequestWithContext(ctx context.Context, method, url string, rawBody interface{}) (*Request, error)
NewRequestWithContext creates a new wrapped request with the provided context.
The context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body.
func (*Request) BodyBytes ¶
BodyBytes allows accessing the request body. It is an analogue to http.Request's Body variable, but it returns a copy of the underlying data rather than consuming it.
This function is not thread-safe; do not call it at the same time as another call, or at the same time this request is being used with Client.Do.
func (*Request) SetBody ¶
SetBody allows setting the request body.
It is useful if a new body needs to be set without constructing a new Request.
func (*Request) SetResponseHandler ¶
func (r *Request) SetResponseHandler(fn ResponseHandlerFunc)
SetResponseHandler allows setting the response handler.
func (*Request) WithContext ¶
WithContext returns wrapped Request with a shallow copy of underlying *http.Request with its context changed to ctx. The provided ctx must be non-nil.
func (*Request) WriteTo ¶
WriteTo allows copying the request body into a writer.
It writes data to w until there's no more data to write or when an error occurs. The return int64 value is the number of bytes written. Any error encountered during the write is also returned. The signature matches io.WriterTo interface.
type RequestLogHook ¶
RequestLogHook allows a function to run before http call executed. The HTTP request which will be made.
type ResolverAdapter ¶
type ResolverAdapter interface {
LoadPolicy(ctx context.Context) error
Resolve(ctx context.Context, req *Request) (*http.Response, error)
}
Main Resolver Contract 1. LoadPolicy : load policy spec from different datastore (file, database, etc...) 2. Resolve : check request and return mock response if exist
func NewFileResolverAdapter ¶
func NewFileResolverAdapter(dir string) (ResolverAdapter, error)
NewFileResolverAdapter returns new ResolverAdapter for Mock client, with file based mock policy.
param: dir (string) -> directory path where all the policy spec located.
type ResponseHandlerFunc ¶
ResponseHandlerFunc is a type of function that takes in a Response, and does something with it. The ResponseHandlerFunc is called when the HTTP client successfully receives a response and the The response body is not automatically closed. It must be closed either by the ResponseHandlerFunc or by the caller out-of-band. Failure to do so will result in a memory leak.
Main purposes: to enable delay for mocking http calls
type ResponseLogHook ¶
ResponseLogHook is like RequestLogHook, but allows running a function on each HTTP response. This function will be invoked at the end of every HTTP request executed, regardless of whether a subsequent retry needs to be performed or not. If the response body is read or closed from this method, this will affect the response returned from Do().