-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.go
141 lines (102 loc) · 2.4 KB
/
fetch.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
129
130
131
132
133
134
135
136
137
138
139
140
141
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"regexp"
"sync"
"time"
"github.com/jochasinga/requests"
)
func addAuthQuery(r *requests.Request) {
r.Params.Add("app_id", apiCreds.AppID)
r.Params.Add("app_key", apiCreds.AppKey)
}
func fetchLineStopPairs(ps []Pair) ([]Times, error) {
pairReg := regexp.MustCompile(`\/`)
var data []Times
pairLen := len(ps)
urls := make([]string, pairLen)
for i, p := range ps {
urls[i] = fmt.Sprintf("%v/ibus/lines/%v/stops/%v", baseURL, p.Line, p.Stop)
}
pool := requests.NewPool(pairLen)
results, err := pool.Get(urls, addAuthQuery)
if err != nil {
log.Println(err)
return data, errors.New("could not create request pool")
}
errCount := 0
for res := range results {
if res.Error != nil {
log.Println(res.Error)
errCount++
continue
}
var tmp APIResponse
json.Unmarshal(res.Bytes(), &tmp)
tmpPair := pairReg.Split(res.Response.Request.URL.Path, -1)
var (
tmpLine string
tmpStop string
)
if len(tmpPair) > 5 {
tmpLine = tmpPair[4]
tmpStop = tmpPair[6]
} else {
tmpLine = "?line"
tmpStop = "?stop"
}
tmpTimes := Times{0, Pair{tmpLine, tmpStop}, 0.0}
if len(tmp.Data.IBus) > 0 {
tmpTimes.Time = tmp.Data.IBus[0].TimeS
}
data = append(data, tmpTimes)
}
if errCount != 0 {
log.Printf("Error count: %v\n", errCount)
return data, errors.New("there were errors during pool request resolve")
}
return data, nil
}
func fetchLineStopPairAsync(wg *sync.WaitGroup, id int, p Pair, d *Times) {
defer deferDone(wg, time.Now(), id, d)
var empty Times
url := fmt.Sprintf("%v/ibus/lines/%v/stops/%v", baseURL, p.Line, p.Stop)
rc, err := requests.GetAsync(url, addAuthQuery)
if err != nil {
log.Println(err)
d = &empty
return
}
res := <-rc
if res.Error != nil {
log.Println(err)
d = &empty
return
}
var tmp APIResponse
d.Meta = p
json.Unmarshal(res.Bytes(), &tmp)
if len(tmp.Data.IBus) > 0 {
d.Time = tmp.Data.IBus[0].TimeS
}
}
func fetchLineStopPairSync(wg *sync.WaitGroup, id int, p Pair, d *Times) {
defer deferDone(wg, time.Now(), id, d)
var empty Times
url := fmt.Sprintf("%v/ibus/lines/%v/stops/%v", baseURL, p.Line, p.Stop)
res, err := requests.Get(url, addAuthQuery)
if err != nil {
log.Println(err)
d = &empty
return
}
var tmp APIResponse
d.Meta = p
json.Unmarshal(res.Bytes(), &tmp)
if len(tmp.Data.IBus) > 0 {
d.Time = tmp.Data.IBus[0].TimeS
}
}