/
search.go
58 lines (49 loc) · 1.23 KB
/
search.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
package wikipedia
import (
"context"
"errors"
"github.com/samber/lo"
)
// SearchOptions are the options for the Wikipedia search request.
type SearchOptions struct {
Limit int // the max number of results returned, default 10
}
func defaultSearchOptions() *SearchOptions {
return &SearchOptions{Limit: defaultLimit}
}
type searchRequest struct {
Action Action `url:"action"`
List string `url:"list"`
SrProp string `url:"srprop"`
SrLimit int `url:"srlimit"`
Limit int `url:"limit"`
SrSearch string `url:"srsearch"`
Format string `url:"format"`
}
// Search searches the Wikipedia for the given query.
func (c *Client) Search(
ctx context.Context,
query string,
options ...func(searchOptions *SearchOptions),
) ([]string, error) {
if len(query) == 0 {
return nil, errors.New("go-wikipedia: query is empty")
}
o := defaultSearchOptions()
for _, option := range options {
option(o)
}
req := &searchRequest{
Action: ActionQuery,
List: "search",
SrLimit: o.Limit,
Limit: o.Limit,
SrSearch: query,
Format: "json",
}
resp, err := c.do(ctx, req)
if err != nil {
return nil, err
}
return lo.Map(resp.Query.Search, func(item *searchResponse, _ int) string { return item.Title }), nil
}