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 ¶
BasicAuth middleware requires basic auth and matches user & passwd with client-provided checker
func BasicAuthWithArgon2Hash ¶
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 ¶
BasicAuthWithBcryptHash middleware requires basic auth and matches user & bcrypt hashed password
func BasicAuthWithBcryptHashAndPrompt ¶
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 ¶
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 ¶
BasicAuthWithUserPasswd middleware requires basic auth and matches user & passwd with client-provided values
func BlackWords ¶
BlackWords middleware doesn't allow some words in the request body
func BlackWordsFn ¶
BlackWordsFn middleware uses func to get the list and doesn't allow some words in the request body
func CacheControl ¶
CacheControl is a middleware setting cache expiration. Using url+version for etag
func CacheControlDynamic ¶
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 ¶
DecodeJSON decodes json request from http.Request to given type
func Deprecation ¶
Deprecation adds a header 'Deprecation: version="version", date="date" header' see https://tools.ietf.org/id/draft-dalal-deprecation-header-00.html
func EncodeJSON ¶
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 ¶
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 ¶
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 GenerateArgon2Hash ¶
GenerateArgon2Hash generates an argon2 hash and salt from a password
func GenerateBcryptHash ¶
GenerateBcryptHash generates a bcrypt hash from a password
func GetTraceID ¶
GetTraceID returns request id from the context
func Health ¶
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 ¶
IsAuthorized returns true is user authorized. it can be used in handlers to check if BasicAuth middleware was applied
func Maybe ¶
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 ¶
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 ¶
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 ¶
ParseFromTo parses from and to query params of the request
func Profiler ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SizeLimit middleware checks if body size is above the limit and returns StatusRequestEntityTooLarge (413)
Types ¶
type BenchmarkStats ¶
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 ¶
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 ¶
func NewBenchmarks() *Benchmarks
NewBenchmarks creates a new benchmark middleware
func (*Benchmarks) Handler ¶
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 ¶
func (b *Benchmarks) Stats(interval time.Duration) BenchmarkStats
Stats returns the current benchmark stats for the given duration
func (*Benchmarks) WithTimeRange ¶
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 ¶
type ErrorLogger struct {
// contains filtered or unexported fields
}
ErrorLogger wraps logger.Backend
func NewErrorLogger ¶
func NewErrorLogger(l logger.Backend) *ErrorLogger
NewErrorLogger creates ErrorLogger for given Backend
func (*ErrorLogger) Log ¶
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 ¶
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 ¶
NewFileServer creates file server with optional spa mode and optional direcroty listing (disabled by default)