/
ipauth.go
56 lines (46 loc) · 955 Bytes
/
ipauth.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
package ebase
import (
"net"
"net/http"
"reflect"
"strings"
)
type AuthClients []interface{}
func LoadAuthClients(auths string) AuthClients {
clients := make(AuthClients, 0)
ips := strings.Split(auths, ";")
for _, ip := range ips {
if ip == "" {
continue
}
_, ipNet, err := net.ParseCIDR(ip)
if err == nil {
clients = append(clients, ipNet)
} else {
ipHost := net.ParseIP(ip)
if ipHost != nil {
clients = append(clients, ipHost)
}
}
}
return clients
}
func (clients AuthClients) ClientAuthor(ipAddr net.IP) bool {
for _, client := range clients {
vv := reflect.TypeOf(client)
if vv.String() == "*net.IPNet" {
if client.(*net.IPNet).Contains(ipAddr) {
return true
}
} else if vv.String() == "net.IP" {
if client.(net.IP).Equal(ipAddr) {
return true
}
}
}
return false
}
func GetHost(req *http.Request) string {
host, _, _ := net.SplitHostPort(req.RemoteAddr)
return host
}