/
restBuilder.go
263 lines (229 loc) · 7.13 KB
/
restBuilder.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package rest
import (
"github.com/gorilla/mux"
"net/http"
)
// A handler of a rest call
type RestHandler func(*Rest) error
// A decorator decorating a RestHandler
type RestDecorator func(RestHandler) RestHandler
// RestBuilder allows for a Rest endpoint to be built
type RestBuilder struct {
server *Server
commonDecorator []RestDecorator
// pathPrefix
pathPrefix string
pathPrefixRoute *mux.Router
// Below this point are reset after every Build()
authDecorator []RestDecorator
handler RestHandler
headers []string
headersRegexp []string
methods []string
paths []string
queries []string
}
// Begin building rest endpoints on a server
func (s *Server) RestBuilder() *RestBuilder {
return &RestBuilder{server: s}
}
// Build a rest endpoint
func (r *RestBuilder) Build() *RestBuilder {
// Form the final handler with any decorators applied
h := r.handler
// Apply auth decorators
for _, d := range r.authDecorator {
h = d(h)
}
// Apply common decorators
for _, d := range r.commonDecorator {
h = d(h)
}
// The final handler
hf := http.HandlerFunc(Handler(h))
if len(r.paths) == 0 {
// Rare but could happen - e.g. we are not matching against a path but a Header or Query string
r.buildRoute(r.newRoute().Handler(hf))
} else {
for _, path := range r.paths {
r.buildRoute(r.newRoute().Handler(hf).Path(r.pathPrefix + path))
}
}
return r.Reset()
}
func (r *RestBuilder) newRoute() *mux.Route {
if r.pathPrefix != "" {
return r.pathPrefixRoute.NewRoute()
}
return r.server.router.NewRoute()
}
func (r *RestBuilder) buildRoute(route *mux.Route) {
r.applyOption(r.methods, route.Methods)
r.applyOption(r.headers, route.Headers)
r.applyOption(r.headersRegexp, route.HeadersRegexp)
r.applyOption(r.queries, route.Queries)
}
func (r *RestBuilder) applyOption(a []string, f func(...string) *mux.Route) {
if len(a) > 0 {
f(a...)
}
}
// Reset() resets the builder so only the common entries are used in the next
// Build(), e.g. Decorator()'s' and PathPrefix() are affected by this.
//
// Note, Build() call this so it's not normally required
func (r *RestBuilder) Reset() *RestBuilder {
// Reset the builder
r.authDecorator = []RestDecorator{}
r.handler = nil
r.headers = []string{}
r.headersRegexp = []string{}
r.methods = []string{}
r.paths = []string{}
r.queries = []string{}
return r
}
// PathPrefix is the common prefix that will be prepended to all endpoints
// in this builder.
//
// It's preferable if a group of endpoints share the same
// contant prefix, e.g. "/api" to use this not just to save typing the same
// prefix as this will improve performance during matching.
//
// Any trailing "/" are removed.
//
// If the prefix does not start with a "/" then one is prepended.
//
// "" or "/" are treated as no prefix.
func (r *RestBuilder) PathPrefix(pathPrefix string) *RestBuilder {
if pathPrefix == "/" {
pathPrefix = ""
}
if pathPrefix != "" {
if pathPrefix[0:1] != "/" {
pathPrefix = "/" + pathPrefix
}
for len(pathPrefix) > 1 && pathPrefix[len(pathPrefix)-1:] == "/" {
pathPrefix = pathPrefix[0 : len(pathPrefix)-1]
}
}
if pathPrefix == "/" {
pathPrefix = ""
}
r.pathPrefix = pathPrefix
// Create the router for this prefix
if pathPrefix != "" {
r.pathPrefixRoute = r.server.router.NewRoute().
PathPrefix(pathPrefix + "/").
Subrouter()
}
return r
}
// Pattern adds a path to the end point being built.
// You can provide multiple patterns for the call being built
func (r *RestBuilder) Path(s ...string) *RestBuilder {
r.paths = s
// Ensure paths start with "/"
for i, path := range r.paths {
if path != "" && path[0:1] != "/" {
r.paths[i] = "/" + path
}
}
return r
}
// Headers adds a matcher for request header values.
// It accepts a sequence of key/value pairs to be matched. For example:
//
// r := server.RestBuilder()
// r.Headers("Content-Type", "application/json",
// "X-Requested-With", "XMLHttpRequest")
//
// The above route will only match if both request header values match.
// If the value is an empty string, it will match any value if the key is set.
func (r *RestBuilder) Headers(s ...string) *RestBuilder {
r.headers = s
return r
}
// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex
// support. For example:
//
// r := server.RestBuilder()
// r.HeadersRegexp("Content-Type", "application/(text|json)",
// "X-Requested-With", "XMLHttpRequest")
//
// The above route will only match if both the request header matches both regular expressions.
// If the value is an empty string, it will match any value if the key is set.
// Use the start and end of string anchors (^ and $) to match an exact value.
func (r *RestBuilder) HeadersRegexp(s ...string) *RestBuilder {
r.headersRegexp = s
return r
}
// Method sets the HTTP Method this endpoint is to use
func (r *RestBuilder) Method(s ...string) *RestBuilder {
r.methods = s
return r
}
// Queries adds a matcher for URL query values.
// It accepts a sequence of key/value pairs. Values may define variables.
// For example:
//
// r := server.RestBuilder()
// r.Queries("foo", "bar", "id", "{id:[0-9]+}")
//
// The above route will only match if the URL contains the defined queries
// values, e.g.: ?foo=bar&id=42.
//
// It the value is an empty string, it will match any value if the key is set.
//
// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next slash.
//
// - {name:pattern} matches the given regexp pattern.
func (r *RestBuilder) Queries(s ...string) *RestBuilder {
r.queries = s
return r
}
// Handler sets the RestHandler to use for this endpoint
func (r *RestBuilder) Handler(f RestHandler) *RestBuilder {
r.handler = f
return r
}
// Decorate will invoke a RestDecorator against the RestHandler set by Handler()
// to decorate it. This is usually used to add error handling,
// ensuring certain headers are in the response etc.
// Note: This decorator will be used by all endpoints built by this instance
// of the builder. To apply a decorator on a single endpoint use Authenticator()
func (r *RestBuilder) Decorate(f RestDecorator) *RestBuilder {
r.commonDecorator = append(r.commonDecorator, f)
return r
}
// Authenticator is a RestDecorator which is specific to the current endpoint
// being built. It's called Authenticator as it's usually used for authentication
// but it can be used for other purposes.
func (r *RestBuilder) Authenticator(f RestDecorator) *RestBuilder {
r.authDecorator = append(r.authDecorator, f)
return r
}
// AddHeadersDecorator is a decorator which ensures that the given headers
// are always present in a response that has not returned an error.
//
// Here's an example on ensuring certain headers are always present:
//
// Decorate( (&rest.AddHeadersDecorator{
// "Access-Control-Allow-Origin": "*",
// "X-Clacks-Overhead": "GNU Terry Pratchett",
// }).Decorator )
//
type AddHeadersDecorator map[string]string
func (a *AddHeadersDecorator) Decorator(h RestHandler) RestHandler {
return func(r *Rest) error {
err := h(r)
if err == nil {
for k, v := range *a {
r.AddHeader(k, v)
}
}
return err
}
}