This repository has been archived by the owner on Apr 14, 2022. It is now read-only.
forked from asticode/go-astitools
/
middleware.go
216 lines (188 loc) · 5.61 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package astihttp
import (
"context"
"net/http"
"strings"
"time"
"github.com/julienschmidt/httprouter"
"github.com/molotovtv/go-astilog"
"github.com/pkg/errors"
)
// ChainMiddlewares chains middlewares
func ChainMiddlewares(h http.Handler, ms ...Middleware) http.Handler {
return ChainMiddlewaresWithPrefix(h, []string{}, ms...)
}
// ChainMiddlewaresWithPrefix chains middlewares if one of prefixes is present
func ChainMiddlewaresWithPrefix(h http.Handler, prefixes []string, ms ...Middleware) http.Handler {
for _, m := range ms {
if len(prefixes) == 0 {
h = m(h)
} else {
t := h
h = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
for _, prefix := range prefixes {
if strings.HasPrefix(r.URL.EscapedPath(), prefix) {
m(t).ServeHTTP(rw, r)
return
}
}
t.ServeHTTP(rw, r)
})
}
}
return h
}
// ChainRouterMiddlewares chains router middlewares
func ChainRouterMiddlewares(h httprouter.Handle, ms ...RouterMiddleware) httprouter.Handle {
return ChainRouterMiddlewaresWithPrefix(h, []string{}, ms...)
}
// ChainRouterMiddlewares chains router middlewares if one of prefixes is present
func ChainRouterMiddlewaresWithPrefix(h httprouter.Handle, prefixes []string, ms ...RouterMiddleware) httprouter.Handle {
for _, m := range ms {
if len(prefixes) == 0 {
h = m(h)
} else {
t := h
h = func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
for _, prefix := range prefixes {
if strings.HasPrefix(r.URL.EscapedPath(), prefix) {
m(t)(rw, r, p)
return
}
}
t(rw, r, p)
}
}
}
return h
}
// Middleware represents a middleware
type Middleware func(http.Handler) http.Handler
// RouterMiddleware represents a router middleware
type RouterMiddleware func(httprouter.Handle) httprouter.Handle
func handleBasicAuth(username, password string, rw http.ResponseWriter, r *http.Request) bool {
if len(username) > 0 && len(password) > 0 {
if u, p, ok := r.BasicAuth(); !ok || u != username || p != password {
rw.Header().Set("WWW-Authenticate", "Basic Realm=Please enter your credentials")
rw.WriteHeader(http.StatusUnauthorized)
return true
}
}
return false
}
// MiddlewareBasicAuth adds basic HTTP auth to a handler
func MiddlewareBasicAuth(username, password string) Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// Basic auth
if handleBasicAuth(username, password, rw, r) {
return
}
// Next handler
h.ServeHTTP(rw, r)
})
}
}
// RouterMiddlewareBasicAuth adds basic HTTP auth to a router handler
func RouterMiddlewareBasicAuth(username, password string) RouterMiddleware {
return func(h httprouter.Handle) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Basic auth
if handleBasicAuth(username, password, rw, r) {
return
}
// Next handler
h(rw, r, p)
}
}
}
func handleContentType(contentType string, rw http.ResponseWriter) {
rw.Header().Set("Content-Type", contentType)
}
// MiddlewareContentType adds a content type to a handler
func MiddlewareContentType(contentType string) Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// Content type
handleContentType(contentType, rw)
// Next handler
h.ServeHTTP(rw, r)
})
}
}
// RouterMiddlewareContentType adds a content type to a router handler
func RouterMiddlewareContentType(contentType string) RouterMiddleware {
return func(h httprouter.Handle) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Content type
handleContentType(contentType, rw)
// Next handler
h(rw, r, p)
}
}
}
func handleHeaders(vs map[string]string, rw http.ResponseWriter) {
for k, v := range vs {
rw.Header().Set(k, v)
}
}
// MiddlewareHeaders adds headers to a handler
func MiddlewareHeaders(vs map[string]string) Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// Add headers
handleHeaders(vs, rw)
// Next handler
h.ServeHTTP(rw, r)
})
}
}
// RouterMiddlewareHeaders adds headers to a router handler
func RouterMiddlewareHeaders(vs map[string]string) RouterMiddleware {
return func(h httprouter.Handle) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Add headers
handleHeaders(vs, rw)
// Next handler
h(rw, r, p)
}
}
}
func handleTimeout(timeout time.Duration, rw http.ResponseWriter, fn func()) {
// Init context
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Serve
var done = make(chan bool)
go func() {
fn()
done <- true
}()
// Wait for done or timeout
for {
select {
case <-ctx.Done():
astilog.Error(errors.Wrap(ctx.Err(), "astihttp: serving HTTP failed"))
rw.WriteHeader(http.StatusGatewayTimeout)
return
case <-done:
return
}
}
}
// MiddlewareTimeout adds a timeout to a handler
func MiddlewareTimeout(timeout time.Duration) Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
handleTimeout(timeout, rw, func() { h.ServeHTTP(rw, r) })
})
}
}
// RouterMiddlewareTimeout adds a timeout to a router handler
func RouterMiddlewareTimeout(timeout time.Duration) RouterMiddleware {
return func(h httprouter.Handle) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
handleTimeout(timeout, rw, func() { h(rw, r, p) })
}
}
}