-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseragent.go
78 lines (65 loc) · 1.74 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
package commonuseragent
import (
"embed"
"encoding/json"
"math/rand"
"time"
)
// Go directive to embed the files in the binary.
//
//go:embed desktop_useragents.json
//go:embed mobile_useragents.json
var content embed.FS
type UserAgent struct {
UA string `json:"ua"`
Pct float64 `json:"pct"`
}
var desktopAgents []UserAgent
var mobileAgents []UserAgent
func init() {
rand.Seed(time.Now().UnixNano())
loadUserAgents("desktop_useragents.json", &desktopAgents)
loadUserAgents("mobile_useragents.json", &mobileAgents)
}
func loadUserAgents(filename string, agents *[]UserAgent) {
// Reading from the embedded file system
bytes, err := content.ReadFile(filename)
if err != nil {
panic(err)
}
if err := json.Unmarshal(bytes, agents); err != nil {
panic(err)
}
}
func GetAllDesktop() []UserAgent {
return desktopAgents
}
func GetAllMobile() []UserAgent {
return mobileAgents
}
// GetRandomDesktop returns a random UserAgent struct from the desktopAgents slice
func GetRandomDesktop() UserAgent {
if len(desktopAgents) == 0 {
return UserAgent{}
}
return desktopAgents[rand.Intn(len(desktopAgents))]
}
// GetRandomMobile returns a random UserAgent struct from the mobileAgents slice
func GetRandomMobile() UserAgent {
if len(mobileAgents) == 0 {
return UserAgent{}
}
return mobileAgents[rand.Intn(len(mobileAgents))]
}
// GetRandomDesktopUA returns just the UA string of a random desktop user agent
func GetRandomDesktopUA() string {
return GetRandomDesktop().UA
}
// GetRandomMobileUA returns just the UA string of a random mobile user agent
func GetRandomMobileUA() string {
return GetRandomMobile().UA
}
func GetRandomUA() string {
allAgents := append(desktopAgents, mobileAgents...)
return allAgents[rand.Intn(len(allAgents))].UA
}