-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathboard.go
85 lines (74 loc) · 1.54 KB
/
board.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
package getmoe
import (
"fmt"
"io/ioutil"
"net/http"
"time"
)
// Board holds data for API access.
type Board struct {
Provider Provider
httpClient *http.Client
}
// NewBoard creates a new board with provided configuration.
func NewBoard(providerName string, config BoardConfiguration) (*Board, error) {
providersMu.RLock()
provider, ok := providers[providerName]
providersMu.RUnlock()
if !ok {
return nil, fmt.Errorf("getmoe: unknown provider %s", providerName)
}
provider.New(config.Provider)
return &Board{
Provider: provider,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}, nil
}
// NewBoardWithProvider creates a new board with provided configuration.
func NewBoardWithProvider(provider Provider) *Board {
return &Board{
Provider: provider,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
// Request gets images by tags.
func (b *Board) Request() ([]Post, error) {
req, err := b.Provider.PageRequest()
if err != nil {
return nil, err
}
resp, err := b.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
page, err := b.Provider.Parse(body)
if err != nil {
return nil, err
}
return page, nil
}
// RequestAll checks all pages.
func (b *Board) RequestAll() ([]Post, error) {
var pages []Post
for {
b.Provider.NextPage()
page, err := b.Request()
if err != nil {
return pages, err
}
if len(page) == 0 {
break
}
pages = append(pages, page...)
}
return pages, nil
}