-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
95 lines (72 loc) · 1.94 KB
/
main.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
91
92
93
94
95
package main
import (
"context"
"fmt"
"github.com/alexferrari88/gohn/pkg/gohn"
"github.com/alexferrari88/gohn/pkg/processors"
)
func main() {
// Instantiate a new client to retrieve data from the Hacker News API
hn, err := gohn.NewClient(nil)
if err != nil {
panic(err)
}
// Use background context
ctx := context.Background()
// Get the top 500 stories' IDs
topStoriesIds, _ := hn.Stories.GetTopIDs(ctx)
var story *gohn.Item
// Retrieve the details of the first one
if len(topStoriesIds) > 0 && topStoriesIds[0] != nil {
story, _ = hn.Items.Get(ctx, *topStoriesIds[0])
}
if story == nil {
panic("No story found")
}
// Print the story's title
fmt.Println("Title:", *story.Title)
// Print the story's author
fmt.Println("Author:", *story.By)
// Print the story's score
fmt.Println("Score:", *story.Score)
// Print the story's URL
fmt.Println("URL:", *story.URL)
fmt.Println()
fmt.Println()
if story.Kids == nil {
fmt.Println("No comments found")
return
}
// Retrieve all the comments for that story
// UnescapeHTML is applied to each retrieved item to unescape HTML characters
commentsMap, err := hn.Items.FetchAllDescendants(ctx, story, processors.UnescapeHTML())
if err != nil {
panic(err)
}
if len(commentsMap) == 0 {
fmt.Println("No comments found")
return
}
fmt.Printf("Comments found: %d\n", len(commentsMap))
fmt.Println()
// Create a Story struct to hold the story and its comments
storyWithComments := gohn.Story{
Parent: story,
CommentsByIdMap: commentsMap,
}
// Calculate the position of each comment in the story
storyWithComments.SetCommentsPosition()
// Get an ordered list of comments' IDs (ordered by position)
orderedIDs, err := storyWithComments.GetOrderedCommentsIDs()
if err != nil {
panic(err)
}
// Print the comments
for _, id := range orderedIDs {
comment := commentsMap[id]
if comment.Text != nil {
fmt.Println(*comment.Text)
fmt.Println()
}
}
}