-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmiddleware.go
73 lines (61 loc) · 1.88 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package oas
import (
"net/http"
"regexp"
)
// Middleware describes a middleware that can be applied to a http.handler.
type Middleware func(next http.Handler) http.Handler
// MiddlewareOptions represent options for middleware.
type MiddlewareOptions struct {
jsonSelectors []*regexp.Regexp
problemHandler ProblemHandler
continueOnProblem bool
}
// MiddlewareOption represent option for middleware.
type MiddlewareOption func(*MiddlewareOptions)
// WithJSONSelectors returns a middleware option that sets JSON Content-Type selectors.
func WithJSONSelectors(selectors ...*regexp.Regexp) MiddlewareOption {
return func(opts *MiddlewareOptions) {
opts.jsonSelectors = append(opts.jsonSelectors, selectors...)
}
}
// WithProblemHandler returns a middleware option that sets problem handler.
func WithProblemHandler(h ProblemHandler) MiddlewareOption {
return func(opts *MiddlewareOptions) {
opts.problemHandler = h
}
}
// WithProblemHandlerFunc returns a middleware option that sets problem handler.
func WithProblemHandlerFunc(f ProblemHandlerFunc) MiddlewareOption {
return func(opts *MiddlewareOptions) {
opts.problemHandler = f
}
}
// WithContinueOnProblem returns a middleware option that defines if middleware
// should continue when error occurs.
func WithContinueOnProblem(contin bool) MiddlewareOption {
return func(opts *MiddlewareOptions) {
opts.continueOnProblem = contin
}
}
func parseMiddlewareOptions(opts ...MiddlewareOption) MiddlewareOptions {
options := MiddlewareOptions{
jsonSelectors: nil,
continueOnProblem: false,
}
for _, opt := range opts {
opt(&options)
}
if options.jsonSelectors == nil {
defaultJSONSelectors()(&options)
}
return options
}
func defaultJSONSelectors() MiddlewareOption {
return func(opts *MiddlewareOptions) {
opts.jsonSelectors = []*regexp.Regexp{
contentTypeSelectorRegexJSON,
contentTypeSelectorRegexJSONAPI,
}
}
}