|
| 1 | +package opinions |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/url" |
| 9 | + |
| 10 | + "github.com/macie/opinions/http" |
| 11 | +) |
| 12 | + |
| 13 | +// RedditResponse represents some interesting fields of response from Reddit API. |
| 14 | +type RedditResponse struct { |
| 15 | + Data struct { |
| 16 | + Children []struct { |
| 17 | + Data struct { |
| 18 | + ID string `json:"permalink"` |
| 19 | + Title string `json:"title"` |
| 20 | + URL string `json:"url"` |
| 21 | + NumComments int `json:"num_comments"` |
| 22 | + } `json:"data"` |
| 23 | + } `json:"children"` |
| 24 | + } `json:"data"` |
| 25 | +} |
| 26 | + |
| 27 | +// SearchReddit searches Reddit for given query and returns list of discussions |
| 28 | +// sorted by relevance. |
| 29 | +// |
| 30 | +// See: https://www.reddit.com/dev/api#GET_search |
| 31 | +func SearchReddit(ctx context.Context, client http.Client, query string) ([]Discussion, error) { |
| 32 | + discussions := make([]Discussion, 0) |
| 33 | + searchURL := "https://www.reddit.com/search.json?sort=relevance&t=all&q=" |
| 34 | + |
| 35 | + r, err := client.Get(ctx, searchURL+url.QueryEscape(query)) |
| 36 | + if err != nil { |
| 37 | + return discussions, err |
| 38 | + } |
| 39 | + defer r.Body.Close() |
| 40 | + |
| 41 | + if r.StatusCode != http.StatusOK { |
| 42 | + if r.Header.Get("X-Ratelimit-Remaining") == "0" { // https://support.reddithelp.com/hc/en-us/articles/16160319875092-Reddit-Data-API-Wiki |
| 43 | + return discussions, fmt.Errorf("cannot search Reddit: too many requests. Wait %s seconds", r.Header.Get("X-Ratelimit-Reset")) |
| 44 | + } |
| 45 | + |
| 46 | + return discussions, fmt.Errorf("cannot search Reddit: `GET %s` responded with status code %d", r.Request.URL, r.StatusCode) |
| 47 | + } |
| 48 | + |
| 49 | + body, err := io.ReadAll(r.Body) |
| 50 | + if err != nil { |
| 51 | + return discussions, err |
| 52 | + } |
| 53 | + |
| 54 | + var response RedditResponse |
| 55 | + if err := json.Unmarshal(body, &response); err != nil { |
| 56 | + return discussions, err |
| 57 | + } |
| 58 | + |
| 59 | + for _, entry := range response.Data.Children { |
| 60 | + discussions = append(discussions, Discussion{ |
| 61 | + Service: "Reddit", |
| 62 | + URL: "https://reddit.com" + entry.Data.ID, |
| 63 | + Title: entry.Data.Title, |
| 64 | + Source: entry.Data.URL, |
| 65 | + Comments: entry.Data.NumComments, |
| 66 | + }) |
| 67 | + } |
| 68 | + |
| 69 | + return discussions, nil |
| 70 | +} |
0 commit comments