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
|
// Package marginalia implements the Marginalia search API.
//
// You need an API key to use this. See the Marginalia API docs for more information: https://www.marginalia.nu/marginalia-search/api/
package marginalia
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"within.website/x/web"
)
type Request struct {
Query string
Count *int
Index *int
}
type Response struct {
License string `json:"license"`
Query string `json:"query"`
Results []Result `json:"results"`
}
type Result struct {
URL string `json:"url"`
Title string `json:"title"`
Description string `json:"description"`
Quality float64 `json:"quality"`
Details [][]Detail `json:"details"`
}
type Detail struct {
Keyword string `json:"keyword"`
Count int `json:"count"`
FlagsUnstableAPI []string `json:"flagsUnstableAPI"`
}
type Client struct {
apiKey string
httpCli *http.Client
}
func New(apiKey string, httpCli *http.Client) *Client {
if httpCli == nil {
httpCli = &http.Client{}
}
return &Client{
apiKey: apiKey,
httpCli: httpCli,
}
}
func (c *Client) Search(ctx context.Context, req *Request) (*Response, error) {
u, err := url.Parse("https://api.marginalia.nu/")
if err != nil {
return nil, err
}
u.Path = "/" + c.apiKey + "/search/" + url.QueryEscape(req.Query)
q := u.Query()
if req.Count != nil {
q.Set("count", fmt.Sprint(*req.Count))
}
if req.Index != nil {
q.Set("index", fmt.Sprint(*req.Index))
}
u.RawQuery = q.Encode()
r, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
resp, err := c.httpCli.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, web.NewError(http.StatusOK, resp)
}
defer resp.Body.Close()
var result Response
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return &result, nil
}
|