-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStreamCharacters.go
More file actions
50 lines (38 loc) · 921 Bytes
/
StreamCharacters.go
File metadata and controls
50 lines (38 loc) · 921 Bytes
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
package kitsu
import (
"strings"
"time"
)
// StreamCharacters returns a stream of all character objects (async).
func StreamCharacters() chan *Character {
channel := make(chan *Character)
url := "characters?page[limit]=20&page[offset]=0"
ticker := time.NewTicker(500 * time.Millisecond)
rateLimit := ticker.C
go func() {
defer close(channel)
defer ticker.Stop()
for {
page, err := GetCharacterPage(url)
if err != nil {
panic(err)
}
// Feed character data from current page to the stream
for _, character := range page.Data {
channel <- character
}
nextURL := page.Links.Next
// Did we reach the end?
if nextURL == "" {
break
}
// Cut off API base URL
nextURL = strings.TrimPrefix(nextURL, APIBaseURL)
// Continue with the next page
url = nextURL
// Wait for rate limiter to allow the next request
<-rateLimit
}
}()
return channel
}