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 BasicAuthWithArgon2Hash(user, hashedPassword, salt string) func(http.Handler) http.Handler
- func BasicAuthWithBcryptHash(user, hashedPassword string) func(http.Handler) http.Handler
- func BasicAuthWithBcryptHashAndPrompt(user, hashedPassword string) func(http.Handler) http.Handler
- func BasicAuthWithPrompt(user, passwd string) func(http.Handler) http.Handler
- func BasicAuthWithUserPasswd(user, passwd string) 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 DecodeJSON[T any](r *http.Request, res *T) error
- func Deprecation(version string, date time.Time) func(http.Handler) http.Handler
- func EncodeJSON[T any](w http.ResponseWriter, status int, v T) error
- 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 GenerateArgon2Hash(password string) (hash, salt string, err error)
- func GenerateBcryptHash(password string) (string, 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 Health(path string, checkers ...func(ctx context.Context) (name string, err error)) func(http.Handler) http.Handler
- func IsAuthorized(ctx context.Context) bool
- 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 Reject(errCode int, errMsg string, rejectFn func(r *http.Request) bool) func(h 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 BasicAuthWithArgon2Hash ¶ added in v1.20.0
BasicAuthWithArgon2Hash middleware requires basic auth and matches user & argon2 hashed password both hashedPassword and salt must be base64 encoded strings Uses Argon2id with parameters: t=1, m=64*1024 KB, p=4 threads
func BasicAuthWithBcryptHash ¶ added in v1.20.0
BasicAuthWithBcryptHash middleware requires basic auth and matches user & bcrypt hashed password
func BasicAuthWithBcryptHashAndPrompt ¶ added in v1.20.1
BasicAuthWithBcryptHashAndPrompt middleware requires basic auth and matches user & bcrypt hashed password If the user is not authorized, it will prompt for basic auth
func BasicAuthWithPrompt ¶ added in v1.18.0
BasicAuthWithPrompt middleware requires basic auth and matches user & passwd with client-provided values If the user is not authorized, it will prompt for basic auth
func BasicAuthWithUserPasswd ¶ added in v1.17.0
BasicAuthWithUserPasswd middleware requires basic auth and matches user & passwd with client-provided values
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 DecodeJSON ¶ added in v1.19.0
DecodeJSON decodes json request from http.Request to given type
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 EncodeJSON ¶ added in v1.19.0
func EncodeJSON[T any](w http.ResponseWriter, status int, v T) error
EncodeJSON encodes given type to http.ResponseWriter and sets status code and content type header
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 GenerateArgon2Hash ¶ added in v1.20.0
GenerateArgon2Hash generates an argon2 hash and salt from a password
func GenerateBcryptHash ¶ added in v1.20.0
GenerateBcryptHash generates a bcrypt hash from a password
func GetTraceID ¶ added in v1.3.0
GetTraceID returns request id from the context
func Health ¶ added in v1.16.0
func Health(path string, checkers ...func(ctx context.Context) (name string, err error)) func(http.Handler) http.Handler
Health middleware response with health info and status (200 if healthy). Stops chain if health request detected passed checkers implements custom health checks and returns error if health check failed. The check has to return name regardless to the error state. For production usage this middleware should be used with throttler and, optionally, with BasicAuth middlewares
func IsAuthorized ¶ added in v1.17.0
IsAuthorized returns true is user authorized. it can be used in handlers to check if BasicAuth middleware was applied
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 Reject ¶ added in v1.16.0
func Reject(errCode int, errMsg string, rejectFn func(r *http.Request) bool) func(h http.Handler) http.Handler
Reject is a middleware that conditionally rejects requests with a given status code and message. user-defined condition function rejectFn is used to determine if the request should be rejected.
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:"requests"` RequestsSec float64 `json:"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
func (*Benchmarks) WithTimeRange ¶ added in v1.15.6
func (b *Benchmarks) WithTimeRange(maximum time.Duration) *Benchmarks
WithTimeRange sets the maximum time range for the benchmark to keep data for. Default is 15 minutes. The increase of this range will change memory utilization as each second of the range kept as benchData aggregate. The default means 15*60 = 900 seconds of data aggregate. Larger range allows for longer time periods to be benchmarked.
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