This repository has been archived by the owner on Mar 19, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
128 lines (103 loc) · 2.05 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"encoding/csv"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"time"
)
const baseURL = "https://dic.pixiv.net/a/"
const maxWorkers = 5
var re = regexp.MustCompile(`pixivに投稿された作品数: (\d+)`)
func readCsv(path string) ([][]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
return nil, err
}
return records, nil
}
func writeCsv(path string, records [][]string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
writer := csv.NewWriter(file)
err = writer.WriteAll(records)
if err != nil {
return err
}
return nil
}
func fetch(url string) ([]byte, error) {
res, err := http.Get(url)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return body, nil
}
func fetchTagCount(name string) (string, error) {
data, err := fetch(baseURL + name)
if err != nil {
return "", err
}
match := re.FindSubmatch(data)
if match == nil {
return "", fmt.Errorf("not match: %s", name)
}
return string(match[1]), nil
}
func update(records [][]string) error {
today := time.Now().Format("2006-01-02")
records[0] = append(records[0], today)
limit := make(chan struct{}, maxWorkers)
for i, record := range records[1:] {
limit <- struct{}{}
go func(i int, record []string) {
name := record[0]
count, err := fetchTagCount(name)
if err != nil {
log.Fatal(err)
}
log.Println(name, count)
records[i+1] = append(record, count)
<-limit
}(i, record)
}
for i := 0; i < maxWorkers; i++ {
limit <- struct{}{}
}
return nil
}
func main() {
if len(os.Args) != 2 {
log.Fatal("Invalid args: CSV file required")
}
filename := os.Args[1]
records, err := readCsv(filename)
if err != nil {
log.Fatal(err)
}
err = update(records)
if err != nil {
log.Fatal(err)
}
err = writeCsv(filename, records)
if err != nil {
log.Fatal(err)
}
}