-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextractor.go
More file actions
52 lines (42 loc) · 1.19 KB
/
extractor.go
File metadata and controls
52 lines (42 loc) · 1.19 KB
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
package limidder
import (
"fmt"
"net/http"
"strings"
)
type Extractor interface {
ExtractKey(r *http.Request, applyUserRateLimitToAllPaths bool) (string, error)
}
type httpHeaderExtractor struct {
headers []string
fn func([]string) (string, error)
}
func NewHTTPHeadersExtractor(fn func([]string) (string, error), headers ...string) Extractor {
return &httpHeaderExtractor{
headers: headers,
fn: fn,
}
}
func (h *httpHeaderExtractor) ExtractKey(r *http.Request, applyUserRateLimitToAllPaths bool) (string, error) {
values := make([]string, 0, len(h.headers))
// if we can't find a value for the headers, give up and return an error.
var path string
if !applyUserRateLimitToAllPaths {
path = fmt.Sprintf(":%s:%s", r.Method, r.URL.String())
}
if h.fn != nil {
keyString, err := h.fn(h.headers)
if err != nil {
return "", err
}
return fmt.Sprintf("%s%s", keyString, path), nil
}
for _, key := range h.headers {
if value := strings.TrimSpace(r.Header.Get(key)); value == "" {
return "", fmt.Errorf("the header %v must have a value set", key)
} else {
values = append(values, value)
}
}
return fmt.Sprintf("%s%s", strings.Join(values, "-"), path), nil
}