-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreddit.go
70 lines (63 loc) · 1.66 KB
/
reddit.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
package summaraizer
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
// Reddit is a source that fetches comments from a Reddit post.
type Reddit struct {
UrlPath string // The path to the Reddit post. Everything after `https://www.reddit.com`.
}
// Fetch fetches comments from a Reddit post.
func (r *Reddit) Fetch(writer io.Writer) error {
return fetchAndEncode(writer, func() (Comments, error) {
request, err := http.NewRequest("GET", "https://www.reddit.com/"+r.UrlPath+".json", nil)
request.Header.Set("User-Agent", "Go:summaraizer:0.0.0")
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var response []redditResponse
err = json.Unmarshal(body, &response)
if err != nil {
return nil, err
}
var comments Comments
firstPost := response[0].Data.Children[0].Data
fistPostBody := fmt.Sprintf("%s\n\n%s", firstPost.Title, firstPost.Selftext)
comments = append(comments, Comment{
Author: firstPost.Author,
Body: fistPostBody,
})
if len(response) == 2 {
for _, child := range response[1].Data.Children {
comments = append(comments, Comment{
Author: child.Data.Author,
Body: child.Data.Body,
})
}
}
return comments, nil
})
}
type redditResponse struct {
Data struct {
Children []struct {
Data struct {
Author string `json:"author"`
Title string `json:"title,omitempty"`
Selftext string `json:"selftext,omitempty"`
Body string `json:"body,omitempty"`
} `json:"data"`
} `json:"children"`
} `json:"data"`
}