-
Notifications
You must be signed in to change notification settings - Fork 0
/
pages.go
86 lines (72 loc) · 2.19 KB
/
pages.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
package client
import (
"context"
"encoding/json"
_errors "errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"github.com/rl404/fairy/errors/stack"
"github.com/rl404/shimakaze/internal/domain/wikia/entity"
"github.com/rl404/shimakaze/internal/errors"
)
type getPagesResponse struct {
Query struct {
AllPages []struct {
PageID int64 `json:"pageid"`
Title string `json:"title"`
} `json:"allpages"`
} `json:"query"`
Continue struct {
APContinue string `json:"apcontinue"`
} `json:"continue"`
Error struct {
Info string `json:"info"`
} `json:"error"`
}
// GetPages to get pages.
func (c *Client) GetPages(ctx context.Context, limit int, lastName string) ([]entity.Page, string, int, error) {
c.limiter.Take()
url, _ := url.Parse(fmt.Sprintf("%s/api.php", c.host))
q := url.Query()
q.Add("action", "query")
q.Add("format", "json")
q.Add("list", "allpages")
q.Add("apfilterredir", "nonredirects")
q.Add("aplimit", strconv.Itoa(limit))
q.Add("apcontinue", lastName)
url.RawQuery = q.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url.String(), nil)
if err != nil {
return nil, "", http.StatusInternalServerError, stack.Wrap(ctx, err, errors.ErrInternalServer)
}
resp, err := c.http.Do(req)
if err != nil {
return nil, "", http.StatusInternalServerError, stack.Wrap(ctx, err, errors.ErrInternalServer)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, "", resp.StatusCode, stack.Wrap(ctx, _errors.New(http.StatusText(resp.StatusCode)))
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", http.StatusInternalServerError, stack.Wrap(ctx, err, errors.ErrInternalServer)
}
var body getPagesResponse
if err := json.Unmarshal(respBody, &body); err != nil {
return nil, "", http.StatusInternalServerError, stack.Wrap(ctx, err, errors.ErrInternalServer)
}
if body.Error.Info != "" {
return nil, "", http.StatusBadRequest, stack.Wrap(ctx, _errors.New(body.Error.Info))
}
pages := make([]entity.Page, len(body.Query.AllPages))
for i, p := range body.Query.AllPages {
pages[i] = entity.Page{
ID: p.PageID,
Title: p.Title,
}
}
return pages, body.Continue.APContinue, http.StatusOK, nil
}