Documentation ¶
Overview ¶
Package rest provides common middlewares and helpers for rest services
Index ¶
- func AppInfo(app, author, version string) func(http.Handler) http.Handler
- func BasicAuth(checker func(user, passwd string) bool) func(http.Handler) http.Handler
- func BlackWords(words ...string) func(http.Handler) http.Handler
- func BlackWordsFn(fn func() []string) func(http.Handler) http.Handler
- func CacheControl(expiration time.Duration, version string) func(http.Handler) http.Handler
- func CacheControlDynamic(expiration time.Duration, versionFn func(r *http.Request) string) func(http.Handler) http.Handler
- func Deprecation(version string, date time.Time) func(http.Handler) http.Handler
- func FileServer(public, local string, notFound io.Reader) (http.Handler, error)
- func FileServerSPA(public, local string, notFound io.Reader) (http.Handler, error)
- func FsOptListing(fs *FS) error
- func FsOptSPA(fs *FS) error
- func GetTraceID(r *http.Request) string
- func Gzip(contentTypes ...string) func(http.Handler) http.Handler
- func Headers(headers ...string) func(http.Handler) http.Handler
- func Maybe(mw func(http.Handler) http.Handler, maybeFn func(r *http.Request) bool) func(http.Handler) http.Handler
- func Metrics(onlyIps ...string) func(http.Handler) http.Handler
- func NoCache(h http.Handler) http.Handler
- func OnlyFrom(onlyIps ...string) func(http.Handler) http.Handler
- func ParseFromTo(r *http.Request) (from, to time.Time, err error)
- func Ping(next http.Handler) http.Handler
- func Profiler(onlyIps ...string) http.Handler
- func RealIP(h http.Handler) http.Handler
- func Recoverer(l logger.Backend) func(http.Handler) http.Handler
- func RenderJSON(w http.ResponseWriter, data interface{})
- func RenderJSONFromBytes(w http.ResponseWriter, r *http.Request, data []byte) error
- func RenderJSONWithHTML(w http.ResponseWriter, r *http.Request, v interface{}) error
- func Rewrite(from, to string) func(http.Handler) http.Handler
- func SendErrorJSON(w http.ResponseWriter, r *http.Request, l logger.Backend, code int, err error, ...)
- func SizeLimit(size int64) func(http.Handler) http.Handler
- func Throttle(limit int64) func(http.Handler) http.Handler
- func Trace(next http.Handler) http.Handler
- func Wrap(handler http.Handler, mws ...func(http.Handler) http.Handler) http.Handler
- type BenchmarkStats
- type Benchmarks
- type ErrorLogger
- type FS
- type FsOpt
- type JSON
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BasicAuth ¶ added in v1.5.4
BasicAuth middleware requires basic auth and matches user & passwd with client-provided checker
func BlackWords ¶ added in v1.1.0
BlackWords middleware doesn't allow some words in the request body
func BlackWordsFn ¶ added in v1.3.0
BlackWordsFn middleware uses func to get the list and doesn't allow some words in the request body
func CacheControl ¶ added in v1.5.4
CacheControl is a middleware setting cache expiration. Using url+version for etag
func CacheControlDynamic ¶ added in v1.5.4
func CacheControlDynamic(expiration time.Duration, versionFn func(r *http.Request) string) func(http.Handler) http.Handler
CacheControlDynamic is a middleware setting cache expiration. Using url+ func(r) for etag
func Deprecation ¶ added in v1.5.4
Deprecation adds a header 'Deprecation: version="version", date="date" header' see https://tools.ietf.org/id/draft-dalal-deprecation-header-00.html
func FileServer ¶ added in v1.5.4
FileServer is a shortcut for making FS with listing disabled and the custom noFound reader (can be nil). Deprecated: the method is for back-compatibility only and user should use the universal NewFileServer instead
func FileServerSPA ¶ added in v1.5.4
FileServerSPA is a shortcut for making FS with SPA-friendly handling of 404, listing disabled and the custom noFound reader (can be nil). Deprecated: the method is for back-compatibility only and user should use the universal NewFileServer instead
func FsOptListing ¶ added in v1.5.4
FsOptListing turns on directory listing
func GetTraceID ¶ added in v1.3.0
GetTraceID returns request id from the context
func Maybe ¶ added in v1.5.4
func Maybe(mw func(http.Handler) http.Handler, maybeFn func(r *http.Request) bool) func(http.Handler) http.Handler
Maybe middleware will allow you to change the flow of the middleware stack execution depending on return value of maybeFn(request). This is useful for example if you'd like to skip a middleware handler if a request does not satisfy the maybeFn logic. borrowed from https://github.com/go-chi/chi/blob/master/middleware/maybe.go
func NoCache ¶ added in v1.5.4
NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent a router (or subrouter) from being cached by an upstream proxy and/or client.
As per http://wiki.nginx.org/HttpProxyModule - NoCache sets:
Expires: Thu, 01 Jan 1970 00:00:00 UTC Cache-Control: no-cache, private, max-age=0 X-Accel-Expires: 0 Pragma: no-cache (for HTTP/1.0 proxies/clients)
func OnlyFrom ¶ added in v1.1.0
OnlyFrom middleware allows access for limited list of source IPs. Such IPs can be defined as complete ip (like 192.168.1.12), prefix (129.168.) or CIDR (192.168.0.0/16)
func ParseFromTo ¶ added in v1.5.4
ParseFromTo parses from and to query params of the request
func Profiler ¶ added in v1.5.4
Profiler is a convenient subrouter used for mounting net/http/pprof. ie.
func MyService() http.Handler { r := chi.NewRouter() // ..middlewares r.Mount("/debug", middleware.Profiler()) // ..routes return r }
func RealIP ¶ added in v1.5.4
RealIP is a middleware that sets a http.Request's RemoteAddr to the results of parsing either the X-Forwarded-For or X-Real-IP headers.
This middleware should only be used if user can trust the headers sent with request. If reverse proxies are configured to pass along arbitrary header values from the client, or if this middleware used without a reverse proxy, malicious clients could set anything as X-Forwarded-For header and attack the server in various ways.
func Recoverer ¶
Recoverer is a middleware that recovers from panics, logs the panic and returns a HTTP 500 status if possible.
func RenderJSON ¶ added in v1.1.0
func RenderJSON(w http.ResponseWriter, data interface{})
RenderJSON sends data as json
func RenderJSONFromBytes ¶
RenderJSONFromBytes sends binary data as json
func RenderJSONWithHTML ¶
func RenderJSONWithHTML(w http.ResponseWriter, r *http.Request, v interface{}) error
RenderJSONWithHTML allows html tags and forces charset=utf-8
func Rewrite ¶ added in v1.5.4
Rewrite middleware with from->to rule. Supports regex (like nginx) and prevents multiple rewrites example: Rewrite(`^/sites/(.*)/settings/$`, `/sites/settings/$1`
func SendErrorJSON ¶
func SendErrorJSON(w http.ResponseWriter, r *http.Request, l logger.Backend, code int, err error, msg string)
SendErrorJSON sends {error: msg} with error code and logging error and caller
func SizeLimit ¶ added in v1.4.0
SizeLimit middleware checks if body size is above the limit and returns StatusRequestEntityTooLarge (413)
func Throttle ¶ added in v1.5.4
Throttle middleware checks how many request in-fly and rejects with 503 if exceeded
Types ¶
type BenchmarkStats ¶ added in v1.5.4
type BenchmarkStats struct { Requests int `json:"total_requests"` RequestsSec float64 `json:"total_requests_sec"` AverageRespTime int64 `json:"average_resp_time"` MinRespTime int64 `json:"min_resp_time"` MaxRespTime int64 `json:"max_resp_time"` }
BenchmarkStats holds the stats for a given interval
type Benchmarks ¶ added in v1.5.4
type Benchmarks struct {
// contains filtered or unexported fields
}
Benchmarks is a basic benchmarking middleware collecting and reporting performance metrics It keeps track of the requests speeds and counts in 1s benchData buckets ,limiting the number of buckets to maxTimeRange. User can request the benchmark for any time duration. This is intended to be used for retrieving the benchmark data for the last minute, 5 minutes and up to maxTimeRange.
func NewBenchmarks ¶ added in v1.5.4
func NewBenchmarks() *Benchmarks
NewBenchmarks creates a new benchmark middleware
func (*Benchmarks) Handler ¶ added in v1.5.4
func (b *Benchmarks) Handler(next http.Handler) http.Handler
Handler calculates 1/5/10m request per second and allows to access those values
func (*Benchmarks) Stats ¶ added in v1.5.4
func (b *Benchmarks) Stats(interval time.Duration) BenchmarkStats
Stats returns the current benchmark stats for the given duration
type ErrorLogger ¶ added in v1.5.0
type ErrorLogger struct {
// contains filtered or unexported fields
}
ErrorLogger wraps logger.Backend
func NewErrorLogger ¶ added in v1.5.0
func NewErrorLogger(l logger.Backend) *ErrorLogger
NewErrorLogger creates ErrorLogger for given Backend
func (*ErrorLogger) Log ¶ added in v1.5.0
func (e *ErrorLogger) Log(w http.ResponseWriter, r *http.Request, httpCode int, err error, msg ...string)
Log sends json error message {error: msg} with error code and logging error and caller
type FS ¶ added in v1.5.4
type FS struct {
// contains filtered or unexported fields
}
FS provides http.FileServer handler to serve static files from a http.FileSystem, prevents directory listing by default and supports spa-friendly mode (off by default) returning /index.html on 404. - public defines base path of the url, i.e. for http://example.com/static/* it should be /static - local for the local path to the root of the served directory - notFound is the reader for the custom 404 html, can be nil for default
func NewFileServer ¶ added in v1.5.4
NewFileServer creates file server with optional spa mode and optional direcroty listing (disabled by default)
type FsOpt ¶ added in v1.5.4
FsOpt defines functional option type
func FsOptCustom404 ¶ added in v1.5.4
FsOptCustom404 sets custom 404 reader