-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbot_cache.go
61 lines (50 loc) · 1.08 KB
/
bot_cache.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
package devicedetector
import (
"log"
"github.com/gijsbers/go-pcre"
"github.com/robicode/device-detector/util"
)
type BotCache interface {
Find(userAgent string) *CachedBot
}
type EmbeddedBotCache struct {
bots []CachedBot
}
var botFiles = []string{
"bots.yml",
}
func NewEmbeddedBotCache() (*EmbeddedBotCache, error) {
files := NewCacheFileList(botFiles...)
bots, err := parseBots(files)
if err != nil {
return nil, err
}
return &EmbeddedBotCache{
bots: bots,
}, nil
}
func (b *EmbeddedBotCache) Find(userAgent string) *CachedBot {
var matches []CachedBot
for _, bot := range b.bots {
if !bot.compiled && bot.compileError == nil {
re, err := pcre.Compile(util.FixupRegex(bot.Regex), pcre.CASELESS)
if err != nil {
bot.compileError = err
log.Println(err)
continue
}
bot.compiled = true
bot.compiledRegex = re
}
if bot.compileError == nil {
matcher := bot.compiledRegex.MatcherString(userAgent, 0)
if matcher.Matches() {
matches = append(matches, bot)
}
}
}
if len(matches) > 0 {
return &matches[len(matches)-1]
}
return nil
}