-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathrequest_validator.go
More file actions
57 lines (45 loc) · 1.2 KB
/
request_validator.go
File metadata and controls
57 lines (45 loc) · 1.2 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
53
54
55
56
57
package tokenizer
import (
"fmt"
"net/http"
"regexp"
"golang.org/x/exp/maps"
)
type RequestValidator interface {
Validate(r *http.Request) error
}
type allowedHosts map[string]struct{}
var _ RequestValidator = allowedHosts(nil)
func AllowHosts(hosts ...string) RequestValidator {
rh := make(allowedHosts, len(hosts))
for _, h := range hosts {
rh[h] = struct{}{}
}
return rh
}
func (v allowedHosts) Validate(r *http.Request) error {
if r.Host == "" {
return fmt.Errorf("%w: no host in request", ErrBadRequest)
}
if _, allowed := v[r.Host]; !allowed {
return fmt.Errorf("%w: secret not valid for %s", ErrBadRequest, r.Host)
}
return nil
}
func (v allowedHosts) slice() []string {
return maps.Keys(v)
}
type allowedHostPattern regexp.Regexp
var _ RequestValidator = (*allowedHostPattern)(nil)
func AllowHostPattern(pattern *regexp.Regexp) RequestValidator {
return (*allowedHostPattern)(pattern)
}
func (v *allowedHostPattern) Validate(r *http.Request) error {
if r.Host == "" {
return fmt.Errorf("%w: no host in request", ErrBadRequest)
}
if match := (*regexp.Regexp)(v).MatchString(r.Host); !match {
return fmt.Errorf("%w: secret not valid for %s", ErrBadRequest, r.Host)
}
return nil
}