-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseragent.go
More file actions
81 lines (73 loc) · 1.67 KB
/
useragent.go
File metadata and controls
81 lines (73 loc) · 1.67 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package webtools
import (
"net/http"
"net/url"
"strings"
"github.com/mileusna/useragent"
)
// Origin contins request origination context from parsing request headers.
type Origin struct {
Method string
Host string
Forward string
Reference string
UserAgent useragent.UserAgent
}
// From returns the value of the X-Forwarded-For if set, otherwise defaulting
// to the Host header.
func (o *Origin) From() string {
if o.Forward != "" {
return o.Forward
}
return o.Host
}
// Anchor returns a parsed version of the Referer headers, including the domain
// and path without the protocol or query.
func (o *Origin) Anchor() string {
if o.Reference == "" {
return "-"
}
u, _ := url.Parse(o.Reference)
return u.Host + u.Path
}
// String returns the parsed user agent, including only the name and type of
// device being used (or bot).
func (o *Origin) String() string {
var mode string
switch {
case o.UserAgent.Bot:
mode = "bot"
case o.UserAgent.Mobile:
mode = "phone"
case o.UserAgent.Tablet:
mode = "tablet"
case o.UserAgent.Desktop:
mode = "desktop"
default:
mode = "unknown"
}
return o.UserAgent.Name + "/" + mode
}
// Origins parses the request headers to get information about the origins of
// the request, including ...
//
// - Method
// - Host
// - Forwarder
// - Referer
// - User-Agent
func Origins(r *http.Request) *Origin {
method := strings.ToUpper(r.Method)
host := r.Host
forward := r.Header.Get("X-Forwarded-For")
reference := r.Header.Get("Referer")
agent := r.Header.Get("User-Agent")
ua := useragent.Parse(agent)
return &Origin{
Method: method,
Host: host,
Forward: forward,
Reference: reference,
UserAgent: ua,
}
}