Documentation ¶
Overview ¶
Package xhttp provides extended functionality for net/http and go-kit's transport/http packages
Index ¶
- Constants
- Variables
- func ApplyURLParser(parser func(string) (*url.URL, error), values ...string) ([]*url.URL, error)
- func Busy(maxTransactions int) func(http.Handler) http.Handler
- func CheckRedirect(p RedirectPolicy) func(*http.Request, []*http.Request) error
- func DefaultShouldRetry(err error) bool
- func DefaultShouldRetryStatus(status int) bool
- func EnsureRewindable(r *http.Request) error
- func GetErrorEncoder(ctx context.Context) gokithttp.ErrorEncoder
- func IsTemporary(err error) bool
- func NewRewind(r io.Reader) (io.ReadCloser, func() (io.ReadCloser, error), error)
- func NewRewindBytes(b []byte) (io.ReadCloser, func() (io.ReadCloser, error))
- func NewServer(o ServerOptions) *http.Server
- func NewStarter(o StartOptions, s httpServer) func() error
- func NilConstructor(next http.Handler) http.Handler
- func RetryCodes(i int) bool
- func RetryTransactor(o RetryOptions, next func(*http.Request) (*http.Response, error)) func(*http.Request) (*http.Response, error)
- func Rewind(r *http.Request) error
- func ServerKey() string
- func ShouldRetry(err error) bool
- func StaticHeaders(extra http.Header) func(http.Handler) http.Handler
- func WithClient(ctx context.Context, c Client) context.Context
- func WithErrorEncoder(ctx context.Context, ee gokithttp.ErrorEncoder) context.Context
- func WriteError(response http.ResponseWriter, code int, value interface{}) (int, error)
- func WriteErrorf(response http.ResponseWriter, code int, format string, ...) (int, error)
- type BufferedWriter
- type Client
- type Constant
- type Error
- type ReadSeekerCloser
- type RedirectPolicy
- type RetryOptions
- type ServerOptions
- type ShouldRetryFunc
- type ShouldRetryStatusFunc
- type StartOptions
Constants ¶
const (
DefaultMaxRedirects = 10
)
const DefaultRetryInterval = time.Second
Variables ¶
var ErrBufferedWriterClosed = errors.New("BufferedWriter has been closed")
Functions ¶
func ApplyURLParser ¶
ApplyURLParser applies a given URL parser, such as url.Parse or url.ParseRequestURI, to zero or more strings. The resulting slice is ordered the same as the values. Any error halts parsing of subsequent values.
func Busy ¶
Busy creates an Alice-style constructor that limits the number of HTTP transactions handled by decorated handlers. The decorated handler blocks waiting on a semaphore until the request's context is canceled. If a transaction is not allowed to proceed, http.StatusServiceUnavailable.
func CheckRedirect ¶
CheckRedirect produces a redirect policy function given a policy descriptor
func DefaultShouldRetry ¶
DefaultShouldRetry is the default retry predicate. It returns true if and only if err exposes a Temporary() bool method and that method returns true. That means, for example, that for a net.DNSError with the temporary flag set to true this predicate also returns true.
func DefaultShouldRetryStatus ¶
DefaultShouldRetryStatus is the default retry predicate. It returns false on all status codes aka. it will never retry
func EnsureRewindable ¶
EnsureRewindable configures the given request's contents to be restreamed in the event of a redirect or other arbitrary code that must resubmit a request. If this function is successful, Rewind can be used to rewind the request.
If a GetBody function is already present on the request, this function does nothing as the given request is already rewindable. Additionally, if there is no Body on the request, this function does nothing as there's no body to rewind.
func GetErrorEncoder ¶
func GetErrorEncoder(ctx context.Context) gokithttp.ErrorEncoder
GetErrorEncoder returns the go-kit HTTP ErrorEncoder associated with the context. If no encoder is present within the context, DefaultErrorEncoder is returned.
func IsTemporary ¶ added in v2.0.2
func NewRewind ¶
func NewRewind(r io.Reader) (io.ReadCloser, func() (io.ReadCloser, error), error)
NewRewind extracts all remaining bytes from an io.Reader, then uses NewRewindableBytes to produce a body and a get body function. If any error occurred during reading, that error is returned and the other return values will be nil.
This function performs certain optimizations on the returned body and get body function. If r implements io.Seeker, then a get body function that simply invokes Seek(0, 0) is used. Additionally, this function honors the case where r implements io.Closer, preserving its Close() semantics.
func NewRewindBytes ¶
func NewRewindBytes(b []byte) (io.ReadCloser, func() (io.ReadCloser, error))
NewRewindBytes produces both an io.ReadCloser that returns the given bytes and a function that produces a new io.ReadCloser that returns those same bytes. Both return values from this function are appropriate for http.Request.Body and http.Request.GetBody, respectively.
func NewServer ¶
func NewServer(o ServerOptions) *http.Server
NewServer creates a Server from a supplied set of options.
func NewStarter ¶
func NewStarter(o StartOptions, s httpServer) func() error
NewStarter returns a starter closure for the given HTTP server. The start options are first applied to the server instance, and the server instance must not have already been started prior to invoking this method.
The returned closure will invoke the correct method on the server to start it, e.g. Serve, ServeTLS, etc. The selection of which server method is based on the options. For example, if CertificateFile and KeyFile are set, either of the xxxTLS methods will be invoked based on whether there is a Listener configured.
Note: tlsConfig is expected to already be set
func NilConstructor ¶
NilConstructor is an Alice-style decorator for http.Handler instances that does no decoration, i.e. it simply returns its next handler unmodified. This is useful in cases where returning nil from configuration is undesirable. Configuration code can always return a non-nil constructor, using this function in cases where no decoration has been configured.
func RetryCodes ¶ added in v2.0.2
func RetryTransactor ¶
func RetryTransactor(o RetryOptions, next func(*http.Request) (*http.Response, error)) func(*http.Request) (*http.Response, error)
RetryTransactor returns an HTTP transactor function, of the same signature as http.Client.Do, that retries a certain number of times. Note that net/http.RoundTripper.RoundTrip also is of this signature, so this decorator can be used with a RoundTripper or an http.Client equally well.
If o.Retries is nonpositive, next is returned undecorated.
func Rewind ¶
Rewind prepares a request body to be replayed. If a GetBody function is present, that function is invoked. An error is returned if this function could not rewind the request.
func ServerKey ¶
func ServerKey() string
ServerKey returns the contextual logging key for the server name
func ShouldRetry ¶ added in v2.0.2
func StaticHeaders ¶
StaticHeaders returns an Alice-style constructor that emits a static set of headers into every response. If the set of headers is empty, the constructor does no decoration.
func WithClient ¶
WithClient associates an HTTP Client with the context. If the supplied client is nil, the supplied context is returned as is.
func WithErrorEncoder ¶
WithErrorEncoder associates a go-kit ErrorEncoder with the context. If the supplied ErrorEncoder is nil, the supplied context is returned as is.
func WriteError ¶
func WriteError(response http.ResponseWriter, code int, value interface{}) (int, error)
WriteError provides print-style functionality for writing a JSON message as a response. No format parameters are used. The value parameter is subjected to the default stringizing rules of the fmt package.
func WriteErrorf ¶
func WriteErrorf(response http.ResponseWriter, code int, format string, parameters ...interface{}) (int, error)
WriteErrorf provides printf-style functionality for writing out the results of some operation. The response status code is set to code, and a JSON message of the form {"code": %d, "message": "%s"} is written as the response body. fmt.Sprintf is used to turn the format and parameters into a single string for the message.
Although the typical use case for this function is to return a JSON error, this function can be used for non-error responses.
Types ¶
type BufferedWriter ¶
type BufferedWriter struct {
// contains filtered or unexported fields
}
BufferedWriter is a closeable http.ResponseWriter that holds all written response information in memory. The zero value of this type is a fully usable writer.
The http.ResponseWriter methods of this type are not safe for concurrent execution. However, it is safe to invoke Close concurrently with the other methods.
Once closed, future Write and WriteTo calls will return errors. This type is ideal for http.Handler code that should be Buffered and optionally discarded depending on other logic.
func (*BufferedWriter) Close ¶
func (bw *BufferedWriter) Close() error
Close closes this writer. Once closed, this writer will reject writes with an error. This method is idempotent, and will return an error if called more than once on a given writer instance.
func (*BufferedWriter) Header ¶
func (bw *BufferedWriter) Header() http.Header
Header returns the HTTP header to write to the response. This method is unaffected by the close state.
func (*BufferedWriter) Write ¶
func (bw *BufferedWriter) Write(p []byte) (int, error)
Write buffers content for later writing to a real http.ResponseWriter. If this writer is closed, this method returns a count of 0 with an error.
func (*BufferedWriter) WriteHeader ¶
func (bw *BufferedWriter) WriteHeader(code int)
WriteHeader sets a status code and in most other ways behaves as the standard net/http ResponseWriter. This method is idempotent. Only the first invocation will have an effect. If this writer is closed, this method has no effect.
func (*BufferedWriter) WriteTo ¶
func (bw *BufferedWriter) WriteTo(response http.ResponseWriter) (int, error)
WriteTo transfers this writer's state to the given ResponseWriter. This method will only take effect once. Once this method has been invoked successfully, this writer instance is closed and will reject future writes (including this method).
type Constant ¶
Constant represents an http.Handler that writes prebuilt, constant information to the response writer.
type Error ¶
Error is an HTTP-specific carrier of error information. In addition to implementing error, this type also implements go-kit's StatusCoder and Headerer. The json.Marshaler interface is implemented so that the default go-kit error encoder will always emit a JSON message.
func (*Error) MarshalJSON ¶
func (*Error) StatusCode ¶
type ReadSeekerCloser ¶
type ReadSeekerCloser interface { io.ReadSeeker io.Closer }
ReadSeekerCloser combines the behavior of io.Reader, io.Seeker, and io.Closer. This package uses this interface for basic optimizations.
func NopCloser ¶
func NopCloser(rs io.ReadSeeker) ReadSeekerCloser
NopCloser is an analog of io.NopCloser. This function preserves io.Seeker semantics in the returned instance. Additionally, if rs already implements io.Closer, this function returns rs as is.
type RedirectPolicy ¶
type RedirectPolicy struct { // Logger is the go-kit Logger used for logging. If unset, the request context's logger is used. Logger *zap.Logger // MaxRedirects is the maximum number of redirects to follow. If unset, DefaultMaxRedirects is used. MaxRedirects int // ExcludeHeaders is the denylist of headers that should not be copied from previous requests. ExcludeHeaders []string }
RedirectPolicy is the configurable policy for handling redirects
type RetryOptions ¶
type RetryOptions struct { // Logger is the go-kit logger to use. Defaults to sallust.Default() if unset. Logger *zap.Logger // Retries is the count of retries. If not positive, then no transactor decoration is performed. Retries int // Interval is the time between retries. If not set, DefaultRetryInterval is used. Interval time.Duration // Sleep is function used to wait out a duration. If unset, time.Sleep is used. Sleep func(time.Duration) // ShouldRetry is the retry predicate. Defaults to DefaultShouldRetry if unset. ShouldRetry ShouldRetryFunc // ShouldRetryStatus is the retry predicate. Defaults to DefaultShouldRetry if unset. ShouldRetryStatus ShouldRetryStatusFunc // Counter is the counter for total retries. If unset, no metrics are collected on retries. Counter metrics.Counter // UpdateRequest provides the ability to update the request before it is sent. default is noop UpdateRequest func(*http.Request) }
RetryOptions are the configuration options for a retry transactor
type ServerOptions ¶
type ServerOptions struct { // Logger is the go-kit Logger to use for server startup and error logging. If not // supplied, sallust.Default() is used instead. Logger *zap.Logger `json:"-"` // Address is the bind address of the server. If not supplied, defaults to the internal net/http default. Address string `json:"address,omitempty"` // ReadTimeout is the maximum duration for reading the entire request. If not supplied, defaults to the // internal net/http default. ReadTimeout time.Duration `json:"readTimeout,omitempty"` // ReadHeaderTimeout is the amount of time allowed to read request headers. If not supplied, defaults to // the internal net/http default. ReadHeaderTimeout time.Duration `json:"readHeaderTimeout,omitempty"` // WriteTimeout is the maximum duration before timing out writes of the response. If not supplied, defaults // to the internal net/http default. WriteTimeout time.Duration `json:"writeTimeout,omitempty"` // IdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled. // If not supplied, defaults to the internal net/http default. IdleTimeout time.Duration `json:"idleTimeout,omitempty"` // MaxHeaderBytes controls the maximum number of bytes the server will read parsing the request header's // keys and values. If not supplied, defaults to the internal net/http default. MaxHeaderBytes int `json:"maxHeaderBytes,omitempty"` // Listener is the optional net.Listener to use. If not supplied, the http.Server default // listener is used. Listener net.Listener `json:"-"` // DisableKeepAlives indicates whether the server should honor keep alives DisableKeepAlives bool `json:"disableKeepAlives,omitempty"` // CertificateFile is the HTTPS certificate file. If both this field and KeyFile are set, // an HTTPS starter function is created. CertificateFile []string `json:"certificateFile,omitempty"` // KeyFile is the HTTPS key file. If both this field and CertificateFile are set, // an HTTPS starter function is created. KeyFile []string `json:"keyFile,omitempty"` }
ServerOptions describes the superset of options for both construction an http.Server and starting it.
func (*ServerOptions) StartOptions ¶
func (so *ServerOptions) StartOptions() StartOptions
StartOptions produces a StartOptions with the corresponding values from this ServerOptions
type ShouldRetryFunc ¶
ShouldRetryFunc is a predicate for determining if the error returned from an HTTP transaction should be retried.
type ShouldRetryStatusFunc ¶
ShouldRetryStatusFunc is a predicate for determining if the status coded returned from an HTTP transaction should be retried.
type StartOptions ¶
type StartOptions struct { // Logger is the go-kit Logger to use for server startup and error logging. If not // supplied, sallust.Default() is used instead. Logger *zap.Logger `json:"-"` // Listener is the optional net.Listener to use. If not supplied, the http.Server default // listener is used. Listener net.Listener `json:"-"` // DisableKeepAlives indicates whether the server should honor keep alives DisableKeepAlives bool `json:"disableKeepAlives,omitempty"` // CertificateFile is the HTTPS certificate file(s). If both this field and KeyFile are set, // an HTTPS starter function is created. CertificateFile []string `json:"certificateFile,omitempty"` // KeyFile is the HTTPS key file(s). If both this field and CertificateFile are set, // an HTTPS starter function is created. KeyFile []string `json:"keyFile,omitempty"` }
StartOptions represents the subset of server options that have to do with how an HTTP server is started.