-
Notifications
You must be signed in to change notification settings - Fork 2
/
useragent.go
97 lines (82 loc) · 1.6 KB
/
useragent.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package ua
import (
"crypto/rand"
"embed"
_ "embed"
"encoding/json"
"math/big"
)
var (
//go:embed static/*
fs embed.FS
)
// uaType user-agent type
type uaType string
const (
Android uaType = "android"
Chrome uaType = "chrome"
Desktop uaType = "desktop"
Firefox uaType = "firefox"
IE uaType = "ie"
IOS uaType = "ios"
IPad uaType = "ipad"
IPhone uaType = "iphone"
Linux uaType = "linux"
MacOSX uaType = "mac_os_x"
Mobile uaType = "mobile"
Safari uaType = "safari"
)
var (
uaCache = map[uaType]*[]string{
Android: {},
Chrome: {},
Desktop: {},
Firefox: {},
IE: {},
IOS: {},
IPad: {},
IPhone: {},
Linux: {},
MacOSX: {},
Mobile: {},
Safari: {},
}
)
// load data if empty
func load(name uaType) {
var ua = uaCache[name]
if loaded := len(*ua) > 0; loaded {
return
}
var data, _ = fs.ReadFile("static/" + string(name) + ".json")
_ = json.Unmarshal(data, ua)
}
// Random return a random user-agent
func Random() string {
var count = 0
for key, value := range uaCache {
load(key)
count += len(*value)
}
var n, _ = rand.Int(rand.Reader, big.NewInt(int64(count)))
var rnd = int(n.Int64())
for _, value := range uaCache {
var l = len(*value)
if skip := l <= rnd; skip {
rnd -= l
continue
}
return (*value)[rnd]
}
return "" // Unreachable code
}
// RandomType return a random user-agent of the specified type
func RandomType(t uaType) string {
var ua = uaCache[t]
if valid := ua != nil; !valid {
return Random()
}
load(t)
var n, _ = rand.Int(rand.Reader, big.NewInt(int64(len(*ua))))
return (*ua)[n.Int64()]
}