forked from buger/goreplay
/
settings_header_hash_filters.go
68 lines (56 loc) · 1.45 KB
/
settings_header_hash_filters.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
package main
import (
"errors"
"fmt"
"hash/fnv"
"net/http"
"strconv"
"strings"
)
type headerHashFilter struct {
name string
maxHash uint32
}
type HTTPHeaderHashFilters []headerHashFilter
func (h *HTTPHeaderHashFilters) String() string {
return fmt.Sprint(*h)
}
func (h *HTTPHeaderHashFilters) Set(value string) error {
valArr := strings.SplitN(value, ":", 2)
if len(valArr) < 2 {
return errors.New("need both header and value, colon-delimited (ex. user_id:1/2).")
}
fracArr := strings.Split(valArr[1], "/")
if len(fracArr) < 2 {
return errors.New("need both a numerator and denominator specified, slash-delimited (ex. user_id:1/4).")
}
var num, den uint64
num, _ = strconv.ParseUint(fracArr[0], 10, 64)
den, _ = strconv.ParseUint(fracArr[1], 10, 64)
if num < 1 || den < 1 || num > den {
panic("need positive numerators and denominators, with the former less than the latter.")
}
for test := den; test != 1; test /= 2 {
if test%2 == 1 {
return errors.New("must have a denominator which is a power of two.")
}
}
var f headerHashFilter
f.name = valArr[0]
f.maxHash = (uint32)(num * (((uint64)(2 << 31)) / den))
*h = append(*h, f)
return nil
}
func (h *HTTPHeaderHashFilters) Good(req *http.Request) bool {
for _, f := range *h {
if req.Header.Get(f.name) == "" {
return false
}
hasher := fnv.New32a()
hasher.Write([]byte(req.Header.Get(f.name)))
if hasher.Sum32() > f.maxHash {
return false
}
}
return true
}