/
client.go
74 lines (67 loc) · 1.33 KB
/
client.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
69
70
71
72
73
74
package engine
import (
"net"
"net/http"
"strings"
"github.com/ua-parser/uap-go/uaparser"
"github.com/samuelngs/hyper/router"
)
// Client struct
type Client struct {
ip, host, protocol string
device router.Device
req *http.Request
uaparser *uaparser.Parser
}
// IP returns client ip address
func (v *Client) IP() string {
if v.ip == "" {
ip := strings.TrimSpace(v.req.Header.Get("X-Real-Ip"))
if len(ip) > 0 {
v.ip = ip
return ip
}
ip = v.req.Header.Get("X-Forwarded-For")
if index := strings.IndexByte(ip, ','); index >= 0 {
ip = ip[0:index]
}
ip = strings.TrimSpace(ip)
if len(ip) > 0 {
v.ip = ip
return ip
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(v.req.RemoteAddr)); err == nil {
v.ip = ip
return ip
}
}
return v.ip
}
// Host returns request hostname
func (v *Client) Host() string {
if v.host == "" {
v.host = v.req.Host
}
return v.host
}
// Protocol returns protocol name
func (v *Client) Protocol() string {
if v.protocol == "" {
if v.req.TLS != nil {
v.protocol = "https"
} else {
v.protocol = "http"
}
}
return v.protocol
}
// Device returns device information
func (v *Client) Device() router.Device {
if v.device == nil {
v.device = &Device{
req: v.req,
uaparser: v.uaparser,
}
}
return v.device
}