-
Notifications
You must be signed in to change notification settings - Fork 1
/
hn_api.go
90 lines (75 loc) · 1.69 KB
/
hn_api.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
87
88
89
90
package main
import (
"encoding/json"
"sort"
"sync"
"github.com/otiai10/opengraph"
"net/http"
"strconv"
)
// HackerNews store entry on hackernews.
type HackerNews struct {
n int
By string `json:"by"`
Score int `json:"score"`
Title string `json:"title"`
Type string `json:"type"`
URL string `json:"url"`
Description string
}
// GetHackerNewsDetail return entries's detail on hackernews.
func GetHackerNewsDetail(ids []int) ([]HackerNews, error) {
var wg sync.WaitGroup
var hns []HackerNews
var chn = make(chan HackerNews, len(ids))
for _, s := range ids {
wg.Add(1)
go func(s int) {
defer wg.Done()
url := "https://hacker-news.firebaseio.com/v0/item/" + strconv.Itoa(s) + ".json?print=pretty"
var hn HackerNews
hn.n = s
res, err := http.Get(url)
if err != nil {
return
}
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&hn)
if err != nil {
return
}
if hn.URL != "" {
og, err := opengraph.Fetch(hn.URL)
if err != nil {
return
}
hn.Description = og.Description
}
chn <- hn
}(s)
}
wg.Wait()
close(chn)
for e := range chn {
hns = append(hns, e)
}
sort.Slice(hns, func(i, j int) bool {
return hns[i].n < hns[j].n
})
return hns, nil
}
// GetHackerNews return entries on hackernews.
func GetHackerNews(n int) ([]HackerNews, error) {
res, err := http.Get("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty")
if err != nil {
return nil, err
}
defer res.Body.Close()
var idHn []int
err = json.NewDecoder(res.Body).Decode(&idHn)
if err != nil {
return nil, err
}
//var hns []HackerNews
return GetHackerNewsDetail(idHn[0 : n-1])
}