Documentation
¶
Index ¶
- Constants
- Variables
- func CacheControl(d time.Duration, private bool) string
- func SetCacheHeader(r *ResponseWriter, d time.Duration)
- func SetCacheHeaderPrivate(r *ResponseWriter, d time.Duration, private bool)
- func WithAuthorization(value string) clientOptionFunc
- func WithBaseUrl(value string) clientOptionFunc
- func WithClientRedactNames(patterns ...string) clientOptionFunc
- func WithContext(value context.Context) requestOptionFunc
- func WithHeader(key, value string) requestOptionFunc
- func WithIdleTimeout(d time.Duration) serverOption
- func WithJsonPayload(value interface{}) requestOptionFunc
- func WithLogger(l *zap.Logger) serverOption
- func WithMaxHeaderBytes(n int) serverOption
- func WithMaxResponseBytes(n int64) clientOptionFunc
- func WithMode(m Mode) serverOption
- func WithPort(v string) serverOption
- func WithPortInt(v int64) serverOption
- func WithReadHeaderTimeout(d time.Duration) serverOption
- func WithReadTimeout(d time.Duration) serverOption
- func WithRedactNames(patterns ...string) serverOption
- func WithResponseWriter(res *ResponseWriter) (*ResponseWriter, *ResponseWriterInterceptor)
- func WithShutdownTimeout(d time.Duration) serverOption
- func WithSource(m, u string) requestOptionFunc
- func WithStringPayload(value string) requestOptionFunc
- func WithTemplates(v string) serverOption
- func WithTimeout(value time.Duration) clientOptionFunc
- func WithTransport(value *http.Transport) clientOptionFunc
- func WithTrustedProxies(cidrs ...string) serverOption
- func WithWriteTimeout(d time.Duration) serverOption
- type BreakerOptions
- type CircuitBreaker
- type Client
- type CorsOptions
- type Handler
- type HandlerFunc
- type MiddlewareHandlerFunc
- type Mode
- type Request
- func (req *Request) Accepts(value string) bool
- func (req *Request) Body() ([]byte, error)
- func (req *Request) BodyJSON(v interface{}) error
- func (req *Request) BodyString() (string, error)
- func (req *Request) Context() context.Context
- func (req *Request) Cookie(name string) string
- func (req *Request) Header(name string) string
- func (req *Request) Host() string
- func (req *Request) Hostname() string
- func (req *Request) Logger() *zap.Logger
- func (req *Request) Method() string
- func (req *Request) Origin() string
- func (req *Request) Param(name string) string
- func (req *Request) Path() string
- func (req *Request) Protocol() string
- func (req *Request) Query(name string) string
- func (req *Request) RoutePath() string
- func (req *Request) UserAgent() string
- func (req *Request) WithContext(ctx context.Context) *Request
- type Response
- type ResponseWriter
- func (res *ResponseWriter) Append(name string, values ...string)
- func (res *ResponseWriter) ClearCookie(name string)
- func (res *ResponseWriter) Cookie(cookie *http.Cookie)
- func (res *ResponseWriter) End()
- func (res *ResponseWriter) Error(e error)
- func (res *ResponseWriter) Flush()
- func (res *ResponseWriter) FlushError() error
- func (res *ResponseWriter) Header() http.Header
- func (res *ResponseWriter) HeadersSent() bool
- func (res *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (res *ResponseWriter) JSON(v interface{})
- func (res *ResponseWriter) Location(value string)
- func (res *ResponseWriter) Own(name, value string)
- func (res *ResponseWriter) OwnVary(names ...string)
- func (res *ResponseWriter) ReadFrom(r io.Reader) (int64, error)
- func (res *ResponseWriter) Redirect(value string)
- func (res *ResponseWriter) Remove(name string)
- func (res *ResponseWriter) Render(name string, data interface{})
- func (res *ResponseWriter) Send(v []byte)
- func (res *ResponseWriter) SendFile(name string)
- func (res *ResponseWriter) SendStatus(code int)
- func (res *ResponseWriter) Set(name, value string)
- func (res *ResponseWriter) Status(code int)
- func (res *ResponseWriter) StatusCode() int
- func (res *ResponseWriter) String(v string)
- func (res *ResponseWriter) Unwrap() http.ResponseWriter
- func (res *ResponseWriter) Vary(names ...string)
- func (res *ResponseWriter) Write(b []byte) (int, error)
- func (res *ResponseWriter) WriteHeader(code int)
- type ResponseWriterInterceptor
- type Router
- func (r *Router) CONNECT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (r *Router) DELETE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (r *Router) GET(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (r *Router) Handle(method, pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (r *Router) PATCH(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (r *Router) POST(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (r *Router) PUT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (r *Router) Route(prefix string, m ...MiddlewareHandlerFunc) *Router
- func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (r *Router) TRACE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (r *Router) Use(m ...MiddlewareHandlerFunc)
- type Server
- func (s *Server) CONNECT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (s *Server) DELETE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (s *Server) GET(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (s *Server) Listen(c context.Context) error
- func (s *Server) PATCH(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (s *Server) POST(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (s *Server) PUT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (s *Server) Route(prefix string, m ...MiddlewareHandlerFunc) *Router
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) TRACE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
- func (s *Server) Use(m ...MiddlewareHandlerFunc)
Constants ¶
const ( MethodGet = http.MethodGet MethodHead = http.MethodHead MethodPost = http.MethodPost MethodPut = http.MethodPut MethodPatch = http.MethodPatch MethodDelete = http.MethodDelete MethodConnect = http.MethodConnect MethodOptions = http.MethodOptions MethodTrace = http.MethodTrace )
HTTP methods were copied from net/http.
const ( HeaderAccept = "Accept" HeaderAcceptRanges = "Accept-Ranges" HeaderAcceptLanguage = "Accept-Language" HeaderAcceptEncoding = "Accept-Encoding" // HeaderAllow is the name of the "Allow" header field used to list the set of methods // advertised as supported by the target resource. Returning an Allow header is mandatory // for status 405 (method not found) and useful for the OPTIONS method in responses. // See RFC 7231: https://datatracker.ietf.org/doc/html/rfc7231#section-7.4.1 HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLanguage = "Content-Language" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfMatch = "If-Match" HeaderIfNoneMatch = "If-None-Match" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderRetryAfter = "Retry-After" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedHost = "X-Forwarded-Host" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXRealIP = "X-Real-Ip" HeaderXRequestID = "X-Request-Id" HeaderXCorrelationID = "X-Correlation-Id" HeaderXRequestedWith = "X-Requested-With" HeaderServer = "Server" HeaderOrigin = "Origin" HeaderCacheControl = "Cache-Control" HeaderConnection = "Connection" HeaderEtag = "Etag" HeaderUserAgent = "User-Agent" HeaderRange = "Range" HeaderContentRange = "Content-Range" HeaderPragma = "Pragma" HeaderReferrer = "Referrer" HeaderPriority = "Priority" // Access control HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" // Security HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderXCSRFToken = "X-CSRF-Token" HeaderReferrerPolicy = "Referrer-Policy" HeaderSecFetchSite = "Sec-Fetch-Site" HeaderSecFetchDest = "Sec-Fetch-Dest" HeaderSecFetchUser = "Sec-Fetch-User" HeaderSecFetchMode = "Sec-Fetch-Mode" HeaderSecChUa = "Sec-Ch-Ua" HeaderSecCHUaMobile = "Sec-Ch-Ua-Mobile" HeaderSecChUaPlatform = "Sec-Ch-Ua-Platform" )
const ( // MIMEApplicationJSON JavaScript Object Notation (JSON) https://www.rfc-editor.org/rfc/rfc8259 MIMEApplicationJSON = "application/json" // Deprecated: Please use MIMEApplicationJSON instead. JSON should be encoded using UTF-8 by default. // No "charset" parameter is defined for this registration. // Adding one really has no effect on compliant recipients. // See RFC 8259, section 8.1. https://datatracker.ietf.org/doc/html/rfc8259#section-8.1 MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8 MIMETextXML = "text/xml" MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8 MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationMsgpack = "application/msgpack" MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8 MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8 MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" )
MIME types that are commonly used
const ( StatusContinue = http.StatusContinue StatusSwitchingProtocols = http.StatusSwitchingProtocols StatusProcessing = http.StatusProcessing StatusEarlyHints = http.StatusEarlyHints StatusOK = http.StatusOK StatusCreated = http.StatusCreated StatusAccepted = http.StatusAccepted StatusNonAuthoritativeInformation = http.StatusNonAuthoritativeInfo StatusNoContent = http.StatusNoContent StatusResetContent = http.StatusResetContent StatusPartialContent = http.StatusPartialContent StatusMultiStatus = http.StatusMultiStatus StatusAlreadyReported = http.StatusAlreadyReported StatusIMUsed = http.StatusIMUsed StatusMultipleChoices = http.StatusMultipleChoices StatusMovedPermanently = http.StatusMovedPermanently StatusFound = http.StatusFound StatusSeeOther = http.StatusSeeOther StatusNotModified = http.StatusNotModified StatusUseProxy = http.StatusUseProxy StatusSwitchProxy = 306 StatusTemporaryRedirect = http.StatusTemporaryRedirect StatusPermanentRedirect = http.StatusPermanentRedirect StatusBadRequest = http.StatusBadRequest StatusPaymentRequired = http.StatusPaymentRequired StatusForbidden = http.StatusForbidden StatusNotFound = http.StatusNotFound StatusMethodNotAllowed = http.StatusMethodNotAllowed StatusNotAcceptable = http.StatusNotAcceptable StatusProxyAuthRequired = http.StatusProxyAuthRequired StatusRequestTimeout = http.StatusRequestTimeout StatusConflict = http.StatusConflict StatusGone = http.StatusGone StatusLengthRequired = http.StatusLengthRequired StatusPreconditionFailed = http.StatusPreconditionFailed StatusRequestEntityTooLarge = http.StatusRequestEntityTooLarge StatusRequestURITooLong = http.StatusRequestURITooLong StatusUnsupportedMediaType = http.StatusUnsupportedMediaType StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable StatusExpectationFailed = http.StatusExpectationFailed StatusTeapot = http.StatusTeapot StatusMisdirectedRequest = http.StatusMisdirectedRequest StatusUnprocessableEntity = http.StatusUnprocessableEntity StatusLocked = http.StatusLocked StatusFailedDependency = http.StatusFailedDependency StatusTooEarly = http.StatusTooEarly StatusUpgradeRequired = http.StatusUpgradeRequired StatusPreconditionRequired = http.StatusPreconditionRequired StatusTooManyRequests = http.StatusTooManyRequests StatusRequestHeaderFieldsTooLarge = http.StatusRequestHeaderFieldsTooLarge StatusInternalServerError = http.StatusInternalServerError StatusNotImplemented = http.StatusNotImplemented StatusBadGateway = http.StatusBadGateway StatusGatewayTimeout = http.StatusGatewayTimeout StatusHTTPVersionNotSupported = http.StatusHTTPVersionNotSupported StatusVariantAlsoNegotiates = http.StatusVariantAlsoNegotiates StatusInsufficientStorage = http.StatusInsufficientStorage StatusLoopDetected = http.StatusLoopDetected StatusNotExtended = http.StatusNotExtended StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired )
Variables ¶
var ErrRequestBodyTooLarge = errors.New("request body too large")
var ErrResponseTooLarge = errors.New("response body too large")
ErrResponseTooLarge is returned by Response.JSON, String and Bytes when the body is larger than the limit of WithMaxResponseBytes.
Functions ¶
func CacheControl ¶
CacheControl returns the Cache-Control value of SetCacheHeaderPrivate. It has no side effect. A middleware passes it to Own. A duration of zero or less gives no-store: a negative max-age is not valid (RFC 9111 §1.2.2). It does not check the duration: a duration under 1 second gives max-age=0. Use SetCacheHeader in a handler to get the strict check.
func SetCacheHeader ¶
func SetCacheHeader(r *ResponseWriter, d time.Duration)
SetCacheHeader sets Cache-Control with Set. It is for a handler. A middleware that must own the field uses CacheControl with Own.
func SetCacheHeaderPrivate ¶
func SetCacheHeaderPrivate(r *ResponseWriter, d time.Duration, private bool)
SetCacheHeaderPrivate is SetCacheHeader with a private flag. If private is true and d is not 0, the response gets the `private` directive: a shared cache must not store it (RFC 9111 §3.5).
A negative d, and a d above 0 and under 1 second, are mistakes of the developer: max-age takes whole seconds (RFC 9111 §1.2.2). In Development it panics. In Production it logs an error and sends no-store. A d of 1.5s is cut to 1 second.
func WithAuthorization ¶
func WithAuthorization(value string) clientOptionFunc
func WithBaseUrl ¶
func WithBaseUrl(value string) clientOptionFunc
func WithClientRedactNames ¶
func WithClientRedactNames(patterns ...string) clientOptionFunc
WithClientRedactNames adds name patterns to the deny list of the client. It never replaces the default list. The syntax is the one of WithRedactNames. An invalid pattern panics.
func WithContext ¶
func WithHeader ¶
func WithHeader(key, value string) requestOptionFunc
func WithIdleTimeout ¶
WithIdleTimeout sets http.Server.IdleTimeout.
func WithJsonPayload ¶
func WithJsonPayload(value interface{}) requestOptionFunc
func WithLogger ¶
WithLogger sets the logger of the server instead of the preset of WithMode. A nil logger panics. The server never changes the global zap logger.
func WithMaxHeaderBytes ¶
func WithMaxHeaderBytes(n int) serverOption
WithMaxHeaderBytes sets http.Server.MaxHeaderBytes.
func WithMaxResponseBytes ¶
func WithMaxResponseBytes(n int64) clientOptionFunc
WithMaxResponseBytes sets the largest body that Response.JSON, String and Bytes read. A value of 0 means no limit, which is the default. A negative value panics. If Content-Length is known and above the limit, the helpers return ErrResponseTooLarge without a read of the body. Else they stop at one byte over the limit. Response.Body stays unlimited, for streaming. The limit counts decoded bytes when the Transport decompresses gzip. If the caller sets Accept-Encoding by hand, the Transport does not decompress and the limit counts the compressed bytes. The limit is opt-in, as in resty (SetResponseBodyLimit) and req (SetMaxResponseSize).
func WithMode ¶
func WithMode(m Mode) serverOption
WithMode picks the logger preset of the server. WithLogger wins over it, in any order of the options. An error from zap panics at boot.
func WithPort ¶
func WithPort(v string) serverOption
WithPort sets the TCP port. It is a decimal number from 0 to 65535, where 0 lets the OS pick a free port. Any other value panics.
func WithReadHeaderTimeout ¶
WithReadHeaderTimeout sets http.Server.ReadHeaderTimeout. The default is 10 s.
func WithReadTimeout ¶
WithReadTimeout sets http.Server.ReadTimeout.
func WithRedactNames ¶
func WithRedactNames(patterns ...string) serverOption
WithRedactNames adds name patterns to the deny list that hides values in the strict-mode logs and messages. It never replaces the default list (passwords, secrets, tokens, authentication data, sessions, cookies and similar names). A pattern ignores case and treats "-" as "_". "*x*" matches a name that contains x, "*x" a name that ends with x, "x*" a name that starts with x and "x" the name x. An invalid pattern panics.
func WithResponseWriter ¶
func WithResponseWriter(res *ResponseWriter) (*ResponseWriter, *ResponseWriterInterceptor)
WithResponseWriter creates a new ResponseWriter with an interceptor as writer. The interceptor captures the response so a middleware can change it (for example etag) and then send it with SendResponse.
func WithShutdownTimeout ¶
WithShutdownTimeout sets how long Listen waits for in-flight requests after its context is done. The default is 25 s, below the 30 s grace period of Kubernetes. Zero means no limit.
func WithSource ¶
func WithSource(m, u string) requestOptionFunc
func WithStringPayload ¶
func WithStringPayload(value string) requestOptionFunc
func WithTemplates ¶
func WithTemplates(v string) serverOption
func WithTimeout ¶
func WithTransport ¶
func WithTrustedProxies ¶
func WithTrustedProxies(cidrs ...string) serverOption
WithTrustedProxies sets the peers that can send X-Forwarded-* headers. A value is a CIDR, a single IP, or loopback, linklocal or uniquelocal. Without it, no peer is trusted. An invalid value panics.
func WithWriteTimeout ¶
WithWriteTimeout sets http.Server.WriteTimeout.
Types ¶
type BreakerOptions ¶
type BreakerOptions struct {
Name string
// Interval is the length of the rolling window of a closed breaker. Its
// counts roll off bucket by bucket. Zero or less means 10s. The value is
// rounded up to whole seconds (gobreaker adjusts it to a multiple of the 1 s
// bucket). A value under 1s gives one bucket, so it is a fixed window.
Interval time.Duration
Timeout time.Duration
PrometheusGauge *prometheus.GaugeVec
}
type CircuitBreaker ¶
type CircuitBreaker[T any] = gobreaker.CircuitBreaker[T]
func NewCircuitBreaker ¶
func NewCircuitBreaker[T any](opt BreakerOptions) *CircuitBreaker[T]
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func (*Client) Execute ¶
Execute sends the request. A missing method or URL is an error, not a panic. The returned error of a failed request is a *url.Error that holds the URL path. The userinfo and the sensitive query values are masked (see WithClientRedactNames). Only the URL of the error is masked: the text of the wrapped error comes from net/http and can quote a value from the server, for example an unparsable redirect Location. Warn and Error logs of the client show only the scheme, the host and the method.
type CorsOptions ¶
type CorsOptions struct {
Origin []string
Methods []string
Headers []string
Credentials bool
CacheDuration time.Duration
}
CorsOptions sets the CORS policy of the Cors middleware. Origin must list at least one origin ("*" allows every origin). An empty Methods or Headers list means "*".
func DefaultCorsOptions ¶
func DefaultCorsOptions() CorsOptions
DefaultCorsOptions returns a new policy that allows every origin, method and header, with no credentials. Change the copy before you pass it to Cors.
type Handler ¶
type Handler interface {
ServeHTTP(*ResponseWriter, *Request)
}
type HandlerFunc ¶
type HandlerFunc func(res *ResponseWriter, req *Request)
func WrapHandler ¶
func WrapHandler(h http.Handler) HandlerFunc
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(res *ResponseWriter, req *Request)
type MiddlewareHandlerFunc ¶
type MiddlewareHandlerFunc func(next Handler) HandlerFunc
func Cors ¶
func Cors(options CorsOptions) MiddlewareHandlerFunc
Cors returns the CORS middleware (Fetch §3.2). CORS is off unless the developer adds it with Use, on the server or on a group.
A preflight is an OPTIONS request with Origin and Access-Control-Request-Method (Fetch §3.2.2). The middleware answers it with 200, or 403 if the options do not allow it, and the chain ends there: the next middleware and the handler do not run, as a preflight is a standalone request (the same as go-chi/cors, Echo, gin-contrib/cors, Express cors and @fastify/cors). Place Cors before any middleware that can refuse a request without credentials, such as authentication, or the browser gets a refusal with no CORS headers. Any other request gets the CORS response headers, and the chain goes on.
The options are copied. An empty Origin list, Credentials with the "*" origin, an invalid entry and a negative CacheDuration panic at boot.
type Request ¶
func (*Request) Accepts ¶
Accepts reports if the Accept header allows the media type value. The answer depends on Accept, so it adds Accept to Vary (RFC 9110 §12.5.5).
A missing Accept header allows every type. The most specific media range that matches value sets its q value, and q=0 means not acceptable (RFC 9110 §12.4.2). Media type parameters in the header are ignored. An invalid header or an invalid value is never acceptable, so the caller answers with 406.
func (*Request) BodyString ¶
func (*Request) Host ¶
Host returns the Host header. A trusted proxy can set it with X-Forwarded-Host (see WithTrustedProxies).
func (*Request) Logger ¶
Logger returns the logger of the server with the fields request_id, method and route (the registered pattern). A field with an empty value is left out. The first call caches the logger, so a middleware that adds request data (for example RequestId) must run before the first call. It is safe to call from many goroutines.
func (*Request) Param ¶
Param returns a route param. The value is percent-decoded once, per segment (RFC 3986 §2.1). When a value has a ".." part (split on "/", literal or decoded), the router sends 403 and does not call the handler. A decoded NUL or backslash gives 400. A decoded "/" stays as data, and so does a "." part. Still confine a wildcard ("...") value before file use, for example with os.Root or filepath.IsLocal. Static segments compare the raw, still-escaped path, so "/us%65rs" does not match "/users".
type Response ¶
func (*Response) Bytes ¶
Read the response.Body as Bytes. It reads the full body into memory. The limit of WithMaxResponseBytes applies.
func (*Response) GetCacheControlMaxAge ¶
Retrieve the response.Header Cache-Control max-age as time.Duration. All the Cache-Control lines are one list (RFC 9110 section 5.3). The directive name is not case-sensitive, and the value can be a quoted-string (RFC 9111 section 5.2). The value is delta-seconds: digits only (RFC 9111 section 1.2.2), and a value above 2^31 is 2^31. The first max-age directive wins (RFC 9111 section 4.2.1): if its value is invalid the result is zero, which means stale. A quote that does not end stops the scan of that line only: the next line is still read (an invalid directive is ignored).
type ResponseWriter ¶
type ResponseWriter struct {
// contains filtered or unexported fields
}
func (*ResponseWriter) Append ¶
func (res *ResponseWriter) Append(name string, values ...string)
Append adds members to the list field name. All members go in one field line and a member that is already there (same bytes) is skipped. Each element of values is one member: nothing is split. It does nothing after the client is gone.
These are mistakes, as for Set: an empty member (Production skips it), a singleton field such as Content-Type (Production does a Set with the last value), an invalid name or value, Set-Cookie and Vary, a call after the header was sent. A field that a middleware set is not a mistake, as for Set.
Members are compared as whole strings. A value with a quoted comma, such as `rel="x, y"`, is not parsed.
func (*ResponseWriter) ClearCookie ¶
func (res *ResponseWriter) ClearCookie(name string)
ClearCookie asks the client to delete the cookie name (Path "/").
func (*ResponseWriter) Cookie ¶
func (res *ResponseWriter) Cookie(cookie *http.Cookie)
Cookie adds a Set-Cookie field line (RFC 6265 §3). It is the only field that can have many lines. A nil or invalid cookie and a call after the header was sent are mistakes, as for Set: Production does not send the cookie. It does nothing after the client is gone.
func (*ResponseWriter) End ¶
func (res *ResponseWriter) End()
func (*ResponseWriter) Error ¶
func (res *ResponseWriter) Error(e error)
func (*ResponseWriter) Flush ¶
func (res *ResponseWriter) Flush()
Flush implements http.Flusher. See FlushError.
func (*ResponseWriter) FlushError ¶
func (res *ResponseWriter) FlushError() error
FlushError sends the header and flushes the inner writer. It returns http.ErrNotSupported if the inner writer cannot flush (for example an interceptor). http.ResponseController uses it.
func (*ResponseWriter) Header ¶
func (res *ResponseWriter) Header() http.Header
Header returns the raw header map. It is the escape hatch that http.ResponseWriter requires: nothing is validated, merged or checked here. Use Set, Append, Vary, Cookie and Remove for checked changes.
func (*ResponseWriter) HeadersSent ¶
func (res *ResponseWriter) HeadersSent() bool
HeadersSent reports that the header was sent through the ResponseWriter, by a method or by a native handler (see WrapHandler), or, inside an interceptor, that the response was committed to the buffer. It does not track writes made through Unwrap.
func (*ResponseWriter) Hijack ¶
func (res *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements http.Hijacker.
func (*ResponseWriter) JSON ¶
func (res *ResponseWriter) JSON(v interface{})
func (*ResponseWriter) Location ¶
func (res *ResponseWriter) Location(value string)
Location sets the Location field. See Set.
func (*ResponseWriter) Own ¶
func (res *ResponseWriter) Own(name, value string)
Own sets the field name to value. In Development it also records that a middleware set the field. A handler can still change the field (the last writer wins), but Development then logs a warning: the handler overrides a middleware. Production records nothing and logs nothing.
Own is for middleware only. A middleware can call Own again to replace the value that another middleware set. Own has the checks of Set, and Vary and Set-Cookie have their own methods (OwnVary, Cookie). Pass a canonical name (for example "X-Xss-Protection") to avoid an allocation for each request.
func (*ResponseWriter) OwnVary ¶
func (res *ResponseWriter) OwnVary(names ...string)
OwnVary is Vary, and it also keeps each name as a member that the handler cannot remove: Vary only grows (RFC 9110 §12.5.5). Both modes keep the members, and the header re-gets them before it goes out. Like Own, it is for middleware only.
func (*ResponseWriter) ReadFrom ¶
func (res *ResponseWriter) ReadFrom(r io.Reader) (int64, error)
ReadFrom implements io.ReaderFrom, so io.Copy keeps the fast path of the inner writer.
func (*ResponseWriter) Redirect ¶
func (res *ResponseWriter) Redirect(value string)
func (*ResponseWriter) Remove ¶
func (res *ResponseWriter) Remove(name string)
Remove deletes the field name. The mistakes are the same as for Set; Vary has no Remove. It does nothing after the client is gone.
func (*ResponseWriter) Render ¶
func (res *ResponseWriter) Render(name string, data interface{})
func (*ResponseWriter) Send ¶
func (res *ResponseWriter) Send(v []byte)
func (*ResponseWriter) SendFile ¶
func (res *ResponseWriter) SendFile(name string)
SendFile serves the file at the path name. It serves the path that the caller gives, so absolute paths and symbolic links are served. A path with a ".." element gets 404. Do not pass request data without validation.
A status set before SendFile other than 200 is the status of the response: the file is the body, and Range and the conditional fields are not used. Otherwise SendFile sets a strong ETag from the modification time and the size, answers the conditional fields and Range (RFC 9110 sections 13 and 14), and an If-Match or If-None-Match with an invalid syntax gets 400. The ETag is only as strong as the file mtime: a tool that restores the mtime (for example rsync -t, touch -d, or image layers with a fixed mtime) with new content of the same size keeps the same tag (RFC 9110 section 8.8.1).
func (*ResponseWriter) SendStatus ¶
func (res *ResponseWriter) SendStatus(code int)
SendStatus sends the status line and no body. A code outside 200-599 and a call after the header was sent are mistakes, as for Status.
func (*ResponseWriter) Set ¶
func (res *ResponseWriter) Set(name, value string)
Set replaces all values of the field name with value. These are mistakes: an invalid name or value, Set-Cookie and Vary (use Cookie and Vary) and a call after the header was sent. Development panics. Production logs and does not change the field. A field that a middleware set (see Own) is not a mistake: the handler value wins, and Development logs a warning. It does nothing after the client is gone.
func (*ResponseWriter) Status ¶
func (res *ResponseWriter) Status(code int)
Status sets the final status code of the response. A code outside 200-599 and a call after the header was sent are mistakes: Development panics, Production logs and uses 500, or ignores the call after the send.
func (*ResponseWriter) StatusCode ¶
func (res *ResponseWriter) StatusCode() int
StatusCode returns the status of the response. It is 200 until a handler sets another one.
func (*ResponseWriter) String ¶
func (res *ResponseWriter) String(v string)
func (*ResponseWriter) Unwrap ¶
func (res *ResponseWriter) Unwrap() http.ResponseWriter
Unwrap returns the inner writer, for http.ResponseController. A write through it is not tracked by HeadersSent.
func (*ResponseWriter) Vary ¶
func (res *ResponseWriter) Vary(names ...string)
Vary adds names to the Vary field (RFC 9110 §12.5.5). It is the only way to change Vary. Each argument can list names with commas. An empty name is skipped, a name that is already there (ASCII case-insensitive) is skipped and "*" replaces all. Vary stays one field line. An invalid value and a call after the header was sent are mistakes, as for Set. It does nothing after the client is gone. A handler can add members to a Vary that a middleware set, but it cannot remove the members of the middleware.
func (*ResponseWriter) Write ¶
func (res *ResponseWriter) Write(b []byte) (int, error)
Write implements http.ResponseWriter. It sends the header first, with the current status code.
func (*ResponseWriter) WriteHeader ¶
func (res *ResponseWriter) WriteHeader(code int)
WriteHeader implements http.ResponseWriter. Only the first call counts.
type ResponseWriterInterceptor ¶
type ResponseWriterInterceptor struct {
http.ResponseWriter
Buffer *bytes.Buffer
Code int
Size int64
// contains filtered or unexported fields
}
func (*ResponseWriterInterceptor) SendResponse ¶
func (i *ResponseWriterInterceptor) SendResponse(res *ResponseWriter)
func (*ResponseWriterInterceptor) Unwrap ¶
func (i *ResponseWriterInterceptor) Unwrap() http.ResponseWriter
Unwrap returns the real writer under the interceptor.
func (*ResponseWriterInterceptor) Write ¶
func (i *ResponseWriterInterceptor) Write(b []byte) (int, error)
func (*ResponseWriterInterceptor) WriteHeader ¶
func (i *ResponseWriterInterceptor) WriteHeader(code int)
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
func (*Router) CONNECT ¶
func (r *Router) CONNECT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Router) DELETE ¶
func (r *Router) DELETE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Router) GET ¶
func (r *Router) GET(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Router) Handle ¶
func (r *Router) Handle(method, pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
Handle registers a route. A group passes its own middlewares to its parent, so the middlewares of the outer group run first.
func (*Router) PATCH ¶
func (r *Router) PATCH(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Router) POST ¶
func (r *Router) POST(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Router) PUT ¶
func (r *Router) PUT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Router) Route ¶
func (r *Router) Route(prefix string, m ...MiddlewareHandlerFunc) *Router
Route makes a group. The middlewares of a group run on its routes and, for a path under its prefix, on the 404, 405 and OPTIONS answers of the router (see ServeHTTP). A second group with the same prefix, other than a nested group of the first, panics: the answers of that prefix cannot pick one chain. The parameter name does not change the prefix, a regex does.
If a root route and a group route match the same path, the 405 and OPTIONS answers run the root middlewares only, and Allow lists the methods of both routes. To hide the methods of a protected route from unauthenticated clients, put every route of that path in one group that has the authentication middleware. Per-route middleware does not run on the automatic 405 and OPTIONS answers, so Allow still lists a method that only per-route middleware protects.
func (*Router) ServeHTTP ¶
func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves a request. The router answers itself when no route serves it: 404, 405 and the answer to OPTIONS. These answers run the middlewares of the root, and before them the middlewares of one group (the outer group first), so a middleware such as logging or CORS sees them:
- 404: the innermost group whose prefix matches the path.
- 405 and OPTIONS: the group that owns every route that matches the path. If the routes belong to several groups or to the root, only the root middlewares run, as the router cannot pick one group. Allow then lists the methods of all these routes. Per-route middleware never runs on these answers (see Route).
The refusals of an unsafe path value (400, 403) run the root middlewares only, so a group middleware never sees a path that was refused.
OPTIONS without a CORS preflight gets 200 with Allow and no body (RFC 9110 §9.3.7), and 404 for an unknown path. A preflight is answered by the CORS middleware (see Cors).
func (*Router) TRACE ¶
func (r *Router) TRACE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Router) Use ¶
func (r *Router) Use(m ...MiddlewareHandlerFunc)
Use adds middlewares that wrap each route registered after the call. It panics after a route was registered through this router (for a group: through the group or one of its subgroups), as a middleware added later would not wrap that route. Call Use before the routes (the rule of go-chi: "all middlewares must be defined before routes on a mux").
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
func (*Server) CONNECT ¶
func (s *Server) CONNECT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Server) DELETE ¶
func (s *Server) DELETE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Server) GET ¶
func (s *Server) GET(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Server) Listen ¶
Listen serves until c is done, then shuts down gracefully. It returns a bind or serve error. A clean shutdown returns nil.
func (*Server) PATCH ¶
func (s *Server) PATCH(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Server) POST ¶
func (s *Server) POST(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Server) PUT ¶
func (s *Server) PUT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP makes Server an http.Handler that serves requests through its router.
func (*Server) TRACE ¶
func (s *Server) TRACE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)
func (*Server) Use ¶
func (s *Server) Use(m ...MiddlewareHandlerFunc)
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
client
command
|
|
|
server
command
Command server is a short guide to ehttp.
|
Command server is a short guide to ehttp. |
|
internal
|
|
|
ehttptest
Package ehttptest holds the conventions shared by every ehttp test: each assertion carries its basis (a spec section or a reason), and known bugs run as strict expected failures.
|
Package ehttptest holds the conventions shared by every ehttp test: each assertion carries its basis (a spec section or a reason), and known bugs run as strict expected failures. |
|
etag
Package etag reads the entity-tag lists of the If-Match and If-None-Match fields (RFC 9110 section 13.1.1 and 13.1.2).
|
Package etag reads the entity-tag lists of the If-Match and If-None-Match fields (RFC 9110 section 13.1.1 and 13.1.2). |
|
fixtures
Package fixtures holds the servers, handlers and requests that the test suites share.
|
Package fixtures holds the servers, handlers and requests that the test suites share. |
|
hook
Package hook lets the middleware package reach two functions of the ehttp package that are not public API.
|
Package hook lets the middleware package reach two functions of the ehttp package that are not public API. |
|
redact
Package redact masks sensitive values before they reach a log or a message.
|
Package redact masks sensitive values before they reach a log or a message. |
|
test
|
|
|
testapp
Package testapp builds the server that the golden and perf suites test.
|
Package testapp builds the server that the golden and perf suites test. |