-
Notifications
You must be signed in to change notification settings - Fork 1
/
hackernews.go
72 lines (63 loc) · 1.87 KB
/
hackernews.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
package opinions
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
// HackerNewsResponse represents some interesting fields of response from
// HN Search API.
//
// See: https://hn.algolia.com/api
type HackerNewsResponse struct {
Hits []struct {
CreatedAt time.Time `json:"created_at"`
Title string `json:"title"`
URL string `json:"url"`
ObjectID string `json:"objectID"`
NumComments int `json:"num_comments"`
} `json:"hits"`
}
// SearchHackerNews query HN Search API for given prompt. It returns list of
// discussions sorted by relevance, then popularity, then number of comments.
//
// See: https://hn.algolia.com/api
func SearchHackerNews(ctx context.Context, client GetRequester, query string) (discussions []Discussion, err error) {
searchURL := "https://hn.algolia.com/api/v1/search?"
_, err = url.Parse(query)
switch {
case err == nil:
searchURL += "restrictSearchableAttributes=url&query="
default:
searchURL += "tags=story&query="
}
r, err := client.Get(ctx, searchURL+url.QueryEscape(query))
if err != nil {
return noDiscussions, err
}
defer func() {
if closeErr := r.Body.Close(); closeErr != nil && err == nil {
err = closeErr
}
}()
if r.StatusCode != http.StatusOK {
return noDiscussions, fmt.Errorf("GET %s` responded with unexpected status code %d", r.Request.URL, r.StatusCode)
}
var response HackerNewsResponse
if err := json.NewDecoder(r.Body).Decode(&response); err != nil {
return noDiscussions, err
}
discussions = make([]Discussion, 0, len(response.Hits))
for _, entry := range response.Hits {
discussions = append(discussions, Discussion{
Service: "Hacker News",
URL: "https://news.ycombinator.com/item?id=" + url.QueryEscape(entry.ObjectID),
Title: entry.Title,
Source: entry.URL,
Comments: entry.NumComments,
})
}
return discussions, nil
}