-
Notifications
You must be signed in to change notification settings - Fork 20
/
access.go
47 lines (39 loc) · 1.06 KB
/
access.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
package httpx
import (
"net"
"net/http"
"strings"
"time"
"golang.org/x/net/context"
)
// AccessConfig configures what can be accessed
type AccessConfig struct {
ResolveTimeout time.Duration
DisallowedIPs []net.IP
}
// NewAccessConfig creates a new access config
func NewAccessConfig(resolveTimeout time.Duration, disallowedIPs []net.IP) *AccessConfig {
return &AccessConfig{
ResolveTimeout: resolveTimeout,
DisallowedIPs: disallowedIPs,
}
}
// Allow determines whether the given request should be allowed
func (c *AccessConfig) Allow(request *http.Request) (bool, error) {
host := strings.ToLower(request.URL.Hostname())
ctx, cancel := context.WithTimeout(context.Background(), c.ResolveTimeout)
defer cancel()
addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host)
if err != nil {
return false, err
}
// if any of the host's addresses appear in the disallowed list, deny the request
for _, addr := range addrs {
for _, disallowed := range c.DisallowedIPs {
if addr.IP.Equal(disallowed) {
return false, nil
}
}
}
return true, nil
}