-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathlegacy_rank.go
More file actions
99 lines (88 loc) · 1.77 KB
/
Copy pathlegacy_rank.go
File metadata and controls
99 lines (88 loc) · 1.77 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package legacyrank
import (
"archive/zip"
"bytes"
"context"
"encoding/csv"
"errors"
"io"
"log"
"net/http"
"strconv"
"sync"
"time"
)
var ErrNotFound = errors.New("domain not found")
type Getter interface {
GetLegacyRank(domain string) (int, error)
}
type GetterFunc func(domain string) (int, error)
func (f GetterFunc) GetLegacyRank(domain string) (int, error) {
return f(domain)
}
type InMemoryStore struct{}
var once sync.Once
var data map[string]int //map of domain to rank
func NewInMemoryStore() *InMemoryStore {
return &InMemoryStore{}
}
func (s *InMemoryStore) GetLegacyRank(url string) (int, error) {
once.Do(func() {
var err error
data, err = load()
if err != nil {
log.Println(err)
}
})
rank, ok := data[url]
if !ok {
return -1, ErrNotFound
}
return rank, nil
}
func load() (map[string]int, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://s3-us-west-1.amazonaws.com/umbrella-static/top-1m.csv.zip", nil)
if err != nil {
return nil, err
}
client := &http.Client{
Timeout: time.Second * 10,
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
zf, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return nil, err
}
f, err := zf.Open("top-1m.csv")
if err != nil {
return nil, err
}
defer f.Close()
r := csv.NewReader(f)
data := make(map[string]int)
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
rank, err := strconv.Atoi(record[0])
if err != nil {
return nil, err
}
data[record[1]] = rank
}
return data, nil
}