Documentation ¶
Index ¶
- Variables
- func BodyRewindableWithFile(file *os.File) (body io.ReadCloser, getBody func() (io.ReadCloser, error), err error)
- func BodyRewindableWithFilePosition(name string, offset int64, whence int) (body io.ReadCloser, getBody func() (io.ReadCloser, error), err error)
- func CloneMultipartFileHeader(fh *multipart.FileHeader) *multipart.FileHeader
- func CloneMultipartForm(f *multipart.Form) *multipart.Form
- func CloneOrMakeHeader(hdr http.Header) http.Header
- func CloneTLSConfig(cfg *tls.Config) *tls.Config
- func CloneURL(u *url.URL) *url.URL
- func CloneURLValues(v url.Values) url.Values
- func ContentType(content io.Reader, name string) (ctype string, bufferedContent io.Reader, err error)
- func Do(req *http.Request) (*http.Response, error)
- func DoJson(httpReq *http.Request, req, resp interface{}) error
- func DoJsonWithBackoff(httpReq *http.Request, req, resp interface{}, ...) error
- func DoWithBackoff(httpReq *http.Request, opts ...time_.ExponentialBackOffOption) (*http.Response, error)
- func DoesRequestSatisfyTlsTermination(r *http.Request, whitelistedPaths []string, allowedTLSCIDRs []string) error
- func Get(url string) (resp *http.Response, err error)
- func GetProxySchemeAndHost(r *http.Request, allowForwarded bool) (scheme, host string)
- func Head(url string) (resp *http.Response, err error)
- func NewClient(u string) (*http.Client, error)
- func Post(url, contentType string, body io.Reader) (resp *http.Response, err error)
- func PostForm(url string, data url.Values) (resp *http.Response, err error)
- func Recover(writer io.Writer, req *http.Request, ...) interface{}
- func RecoveryServerInterceptor(next http.Handler, out io.Writer, ...) http.Handler
- func RejectInsecureServerInterceptor(next http.Handler, opts ...RejectInsecureOption) *rejectInsecure
- func ReplaceHttpRequestBody(req *http.Request, body io.Reader)
- func ReplacePath(path string, h http.Handler) http.Handler
- func RequestIDFromContext(ctx context.Context) string
- func RequestRewindableWithFileName(name string) (body io.ReadCloser, getBody func() (io.ReadCloser, error), err error)
- func RequestWithBodyRewindable(req *http.Request) error
- func ResolveProxyUrl(u *url.URL, r *http.Request, allowForwarded bool) *url.URL
- func ServeContent(w http.ResponseWriter, r *http.Request, name string, modtime time.Time, ...)
- func ServerWithDefaults(srv *http.Server) *http.Server
- func XRequestIdServerInterceptor(next http.Handler, keys ...interface{}) http.Handler
- type Client
- type EmptyHandlerInterceptorChainOption
- type EmptyRejectInsecureOption
- type HandlerInterceptorChain
- type HandlerInterceptorChainOption
- type HandlerInterceptorChainOptionFunc
- type RejectInsecureOption
- func RejectInsecureWithAllowedTlsCidrs(allowedTLSCIDRs []string) RejectInsecureOption
- func RejectInsecureWithErrorLog(l *log.Logger) RejectInsecureOption
- func RejectInsecureWithForceHttp(forceHttp bool) RejectInsecureOption
- func RejectInsecureWithWhitelistedPaths(whitelistedPaths []string) RejectInsecureOption
- type RejectInsecureOptionFunc
- type RoundTripFunc
- type RoundTripHandler
- type Transport
- func (t *Transport) Abort()
- func (t *Transport) CancelRequest(req *http.Request)
- func (t *Transport) IsAborted() bool
- func (t *Transport) Next(req *http.Request) (resp *http.Response, err error)
- func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)
- func (t *Transport) Use(h ...RoundTripHandler) *Transport
Constants ¶
This section is empty.
Variables ¶
var ( // DefaultCurvePreferences defines the recommended elliptic curves for modern TLS DefaultCurvePreferences = []tls.CurveID{ tls.CurveP256, tls.X25519, } // DefaultCipherSuites defines the recommended cipher suites for modern TLS DefaultCipherSuites = []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, } // DefaultMinVersion defines the recommended minimum version to use for the TLS protocol (1.2) DefaultMinVersion uint16 = tls.VersionTLS12 // DefaultReadTimeout sets the maximum time a client has to fully stream a request (5s) DefaultReadTimeout = 5 * time.Second // DefaultWriteTimeout sets the maximum amount of time a handler has to fully process a request (10s) DefaultWriteTimeout = 10 * time.Second // DefaultIdleTimeout sets the maximum amount of time a Keep-Alive connection can remain idle before // being recycled (120s) DefaultIdleTimeout = 120 * time.Second )
var DefaultXRequestIDKey = "X-Request-ID"
DefaultXRequestIDKey is metadata key name for request ID
var (
ErrBodyNotRewindable = errors.New("body not rewindable")
)
var Methods = []string{ http.MethodOptions, http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace, }
Functions ¶
func BodyRewindableWithFile ¶ added in v0.0.117
func BodyRewindableWithFile(file *os.File) (body io.ReadCloser, getBody func() (io.ReadCloser, error), err error)
RequestRewindableWithFile returns a Request suitable for use with Redirect, like 307 redirect for PUT or POST. Only a nil GetBody in Request may be replace with a rewindable GetBody, which is a Body *os.File. See: https://github.com/golang/go/issues/7912 See also: https://go-review.googlesource.com/c/go/+/29852/13/src/net/http/client.go#391
func BodyRewindableWithFilePosition ¶ added in v0.0.117
func BodyRewindableWithFilePosition(name string, offset int64, whence int) (body io.ReadCloser, getBody func() (io.ReadCloser, error), err error)
func CloneMultipartFileHeader ¶ added in v0.0.120
func CloneMultipartFileHeader(fh *multipart.FileHeader) *multipart.FileHeader
func CloneMultipartForm ¶ added in v0.0.120
func CloneOrMakeHeader ¶ added in v0.0.120
CloneOrMakeHeader invokes Header.Clone but if the result is nil, it'll instead make and return a non-nil Header.
func CloneTLSConfig ¶ added in v0.0.120
CloneTLSConfig returns a shallow clone of cfg, or a new zero tls.Config if cfg is nil. This is safe to call even if cfg is in active use by a TLS client or server.
func ContentType ¶
func Do ¶ added in v0.0.142
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.
func DoJsonWithBackoff ¶ added in v0.0.142
func DoJsonWithBackoff(httpReq *http.Request, req, resp interface{}, opts ...time_.ExponentialBackOffOption) error
DoJsonWithBackoff the same as DoWithBackoff, but bind with json
func DoWithBackoff ¶ added in v0.0.142
func DoWithBackoff(httpReq *http.Request, opts ...time_.ExponentialBackOffOption) (*http.Response, error)
DoWithBackoff will retry by exponential backoff if failed. If request is not rewindable, retry wil be skipped.
func DoesRequestSatisfyTlsTermination ¶
func DoesRequestSatisfyTlsTermination(r *http.Request, whitelistedPaths []string, allowedTLSCIDRs []string) error
DoesRequestSatisfyTlsTermination returns whether the request fulfills tls's constraints, https, path matches any whitelisted paths or ip inclued by any cidr whitelistedPath is http path that does not need to be checked allowedTLSCIDR is the network includes ip.
func GetProxySchemeAndHost ¶
GetProxySchemeAndHost extracts the host and used protocol (either HTTP or HTTPS) from the given request. If `allowForwarded` is set, the X-Forwarded-Host, X-Forwarded-Proto and Forwarded headers will also be checked to support proxies.
func Recover ¶
func Recover(writer io.Writer, req *http.Request, recoverHandler func(err interface{}) interface{}) interface{}
Recover and dump HTTP request if broken pipe
func RecoveryServerInterceptor ¶
func RecoveryServerInterceptor(next http.Handler, out io.Writer, f func(w http.ResponseWriter, r *http.Request, err interface{})) http.Handler
RecoveryServerInterceptor returns a new server interceptors with recovery from panic. affect as recover{f()}; next()
func RejectInsecureServerInterceptor ¶
func RejectInsecureServerInterceptor(next http.Handler, opts ...RejectInsecureOption) *rejectInsecure
RejectInsecureServerInterceptor returns a new server interceptor with tls check. reject the request fulfills tls's constraints,
func ReplaceHttpRequestBody ¶ added in v0.0.142
func ReplacePath ¶
StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.
func RequestIDFromContext ¶
func RequestRewindableWithFileName ¶ added in v0.0.117
func RequestRewindableWithFileName(name string) (body io.ReadCloser, getBody func() (io.ReadCloser, error), err error)
func RequestWithBodyRewindable ¶ added in v0.0.110
RequestWithBodyRewindable returns a Request suitable for use with Redirect, like 307 redirect for PUT or POST. Only a nil GetBody in Request may be replace with a rewindable GetBody, which is a Body replayer. A body with a type not ioutil.NopCloser(nil) may return error as the Body in Request will be closed before redirect automatically. So you can close body by yourself to ensure rewindable always: Examples:
body := req.Body defer body.Close() // body will not be closed inside req.Body = ioutil.NopCloser(body) _ = RequestWithBodyRewindable(req)
// do http requests...
See: https://github.com/golang/go/issues/7912 See also: https://go-review.googlesource.com/c/go/+/29852/13/src/net/http/client.go#391
func ResolveProxyUrl ¶
func ServeContent ¶
func ServeContent(w http.ResponseWriter, r *http.Request, name string, modtime time.Time, content io.Reader, size int64)
ServeContent replies to the request using the content in the provided Reader. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.
If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to DetectContentType. The name is otherwise unused; in particular it can be empty and is never sent in the response.
If modtime is not the zero time or Unix epoch, ServeContent includes it in a Last-Modified header in the response. If the request includes an If-Modified-Since header, ServeContent uses modtime to decide whether the content needs to be sent at all.
If the content's Seek method work: ServeContent uses a seek to the end of the content to determine its size, and the param size is ignored. The same as http.ServeFile If the content's Seek method doesn't work: ServeContent uses the param size to generate a onlySizeSeekable as a pseudo io.ReadSeeker. If size < 0, use chunk or connection close instead
If the caller has set w's ETag header formatted per RFC 7232, section 2.3, ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
Note that *os.File implements the io.ReadSeeker interface.
func ServerWithDefaults ¶ added in v0.0.94
ServerWithDefaults patches a http.Server based on a best practice configuration from Cloudflare: https://blog.cloudflare.com/exposing-go-on-the-internet/
You can override the defaults by mutating the Default* variables exposed by this package
Types ¶
type EmptyHandlerInterceptorChainOption ¶ added in v0.0.28
type EmptyHandlerInterceptorChainOption struct{}
EmptyHandlerInterceptorChainOption does not alter the configuration. It can be embedded in another structure to build custom options.
This API is EXPERIMENTAL.
type EmptyRejectInsecureOption ¶
type EmptyRejectInsecureOption struct{}
EmptyRejectInsecureOption does not alter the configuration. It can be embedded in another structure to build custom options.
This API is EXPERIMENTAL.
type HandlerInterceptorChain ¶ added in v0.0.28
type HandlerInterceptorChain struct {
// contains filtered or unexported fields
}
Workflow interface that allows for customized handler execution chains. Applications can register any number of existing or custom interceptors for certain groups of handlers, to add common preprocessing behavior without needing to modify each handler implementation. A HandlerInterceptor gets called before the appropriate HandlerAdapter triggers the execution of the handler itself. This mechanism can be used for a large field of preprocessing aspects, e.g. for authorization checks, or common handler behavior like locale or theme changes. Its main purpose is to allow for factoring out repetitive handler code. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html
func NewHandlerInterceptorChain ¶ added in v0.0.28
func NewHandlerInterceptorChain(opts ...HandlerInterceptorChainOption) *HandlerInterceptorChain
func (*HandlerInterceptorChain) ApplyOptions ¶ added in v0.0.28
func (o *HandlerInterceptorChain) ApplyOptions(options ...HandlerInterceptorChainOption) *HandlerInterceptorChain
func (HandlerInterceptorChain) InjectHttpHandler ¶ added in v0.0.28
func (chain HandlerInterceptorChain) InjectHttpHandler(next http.Handler) http.Handler
InjectHttpHandler returns a http handler injected by chain
type HandlerInterceptorChainOption ¶ added in v0.0.28
type HandlerInterceptorChainOption interface {
// contains filtered or unexported methods
}
A HandlerInterceptorChainOption sets options.
func WithHandlerInterceptor ¶ added in v0.0.28
func WithHandlerInterceptor( preHandle func(w http.ResponseWriter, r *http.Request) error, wrapHandle func(h http.Handler) http.Handler, postHandle func(w http.ResponseWriter, r *http.Request), afterCompletion func(w http.ResponseWriter, r *http.Request, err interface{}), ) HandlerInterceptorChainOption
type HandlerInterceptorChainOptionFunc ¶ added in v0.0.28
type HandlerInterceptorChainOptionFunc func(*HandlerInterceptorChain)
HandlerInterceptorChainOptionFunc wraps a function that modifies HandlerInterceptorChain into an implementation of the HandlerInterceptorChainOption interface.
type RejectInsecureOption ¶
type RejectInsecureOption interface {
// contains filtered or unexported methods
}
A RejectInsecureOption sets options.
func RejectInsecureWithAllowedTlsCidrs ¶
func RejectInsecureWithAllowedTlsCidrs(allowedTLSCIDRs []string) RejectInsecureOption
RejectInsecureWithAllowedTlsCidrs specifies whether to allow any request which client or proxy's ip included a cidr is a CIDR notation IP address and prefix length, like "192.0.2.0/24" or "2001:db8::/32", as defined in RFC 4632 and RFC 4291.
func RejectInsecureWithErrorLog ¶
func RejectInsecureWithErrorLog(l *log.Logger) RejectInsecureOption
RejectInsecureWithErrorLog specifies an optional logger for errors
func RejectInsecureWithForceHttp ¶
func RejectInsecureWithForceHttp(forceHttp bool) RejectInsecureOption
RejectInsecureWithForceHttp specifies whether to allow any request, as a shortcut circuit
func RejectInsecureWithWhitelistedPaths ¶
func RejectInsecureWithWhitelistedPaths(whitelistedPaths []string) RejectInsecureOption
RejectInsecureWithWhitelistedPaths specifies whether to allow any request which http path matches
type RejectInsecureOptionFunc ¶
type RejectInsecureOptionFunc func(*rejectInsecure)
RejectInsecureOptionFunc wraps a function that modifies rejectInsecure into an implementation of the RejectInsecureOption interface.
type RoundTripFunc ¶
The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.
type RoundTripHandler ¶
func RecoveryClientInterceptor ¶
func RecoveryClientInterceptor(next RoundTripHandler, out io.Writer, f func(resp *http.Response, req *http.Request, err interface{})) RoundTripHandler
RecoveryClientInterceptor returns a new client interceptors with recovery from panic. affect as recover{f()}; next()
func XRequestIdClientInterceptor ¶
func XRequestIdClientInterceptor(next RoundTripHandler, keys ...interface{}) RoundTripHandler
XRequestIdClientInterceptor returns a new client interceptors with x-request-id in context and request's Header.
type Transport ¶
type Transport struct { // Base is the base RoundTripper used to make HTTP requests. // If nil, http.DefaultTransport is used. Base http.RoundTripper // contains filtered or unexported fields }
Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests, wrapping a base RoundTripper and adding an Authorization header with a token from the supplied Sources.
Transport is a low-level mechanism. Most code will use the higher-level Config.Client method instead.
func (*Transport) Abort ¶
func (t *Transport) Abort()
Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.
func (*Transport) CancelRequest ¶
CancelRequest cancels an in-flight request by closing its connection.
func (*Transport) Next ¶
Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler. See example in GitHub.
func (*Transport) RoundTrip ¶
RoundTrip authorizes and authenticates the request with an access token. If no token exists or token is expired, tries to refresh/fetch a new token.
func (*Transport) Use ¶
func (t *Transport) Use(h ...RoundTripHandler) *Transport
Use adds middleware handlers to the transport.
Source Files ¶
- backoff.go
- client.go
- clone.go
- content_range.go
- defaults.go
- fs.go
- handlerinterceptorchain.options.go
- handlerinterceptorchain_options.go
- interceptors.recover.client.go
- interceptors.recover.go
- interceptors.recover.server.go
- interceptors.reject.server.go
- interceptors.server.go
- interceptors.x-request-id.client.go
- interceptors.x-request-id.go
- interceptors.x-request-id.server.go
- method.go
- proxy.go
- range.go
- reject_insecure.option.go
- rejectinsecure_options.go
- rewind.go
- server.go
- transport.go
- transport.handler.go