-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware_get_params.go
41 lines (35 loc) · 1.04 KB
/
middleware_get_params.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
package uhttp
import (
"context"
"fmt"
"net/http"
)
func getParamsMiddleware(u *UHTTP, opts handlerOptions) func(next http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
actualRaw := r.URL.Query() // map[string][]string
actual := map[string]string{}
for key, values := range actualRaw {
if len(values) > 0 {
if len(values) > 1 {
u.RenderError(w, r, fmt.Errorf("param %s has more than one value (given multiple times), this is not supported", key))
return
}
actual[key] = values[0]
}
}
paramMap := R{}
err := u.ValidateParams(opts.requiredGet, actual, paramMap, true)
if err != nil {
u.RenderError(w, r, fmt.Errorf("%v", err))
return
}
err = u.ValidateParams(opts.optionalGet, actual, paramMap, false)
if err != nil {
u.RenderError(w, r, fmt.Errorf("%v", err))
}
ctx := context.WithValue(r.Context(), CtxKeyGetParams, paramMap)
next.ServeHTTP(w, r.WithContext(ctx))
}
}
}