-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
58 lines (46 loc) · 1.41 KB
/
main.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
package user_agent_parse
import (
"net/http"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"go.uber.org/zap"
ua "github.com/mileusna/useragent"
)
func init() {
caddy.RegisterModule(UserAgentParse{})
}
type UserAgentParse struct {
logger *zap.Logger
}
// CaddyModule returns the Caddy module information.
func (UserAgentParse) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.user_agent_parse",
New: func() caddy.Module { return new(UserAgentParse) },
}
}
func (l *UserAgentParse) Provision(ctx caddy.Context) error {
l.logger = ctx.Logger(l)
return nil
}
func (m *UserAgentParse) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
agent := r.Header.Get("User-Agent")
ua := ua.Parse(agent)
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
repl.Set("user_agent.name", ua.Name)
repl.Set("user_agent.version", ua.Version)
repl.Set("user_agent.os", ua.OS)
repl.Set("user_agent.os_version", ua.OSVersion)
repl.Set("user_agent.device", ua.Device)
repl.Set("user_agent.mobile", ua.Mobile)
repl.Set("user_agent.tablet", ua.Tablet)
repl.Set("user_agent.desktop", ua.Desktop)
repl.Set("user_agent.bot", ua.Bot)
repl.Set("user_agent.url", ua.URL)
return next.ServeHTTP(w, r)
}
// Interface guards.
var (
_ caddy.Provisioner = (*UserAgentParse)(nil)
_ caddy.Module = (*UserAgentParse)(nil)
)