File tree Expand file tree Collapse file tree 2 files changed +24
-0
lines changed
Expand file tree Collapse file tree 2 files changed +24
-0
lines changed Original file line number Diff line number Diff line change @@ -23,6 +23,19 @@ type RedditResponse struct {
2323 } `json:"data"`
2424}
2525
26+ // UnmarshalJSON deserialize inconsistent JSON responses to RedditResponse.
27+ // Reddit returns empty object ("{}") when there are no search results.
28+ func (r * RedditResponse ) UnmarshalJSON (b []byte ) error {
29+ isEmptyResponse := len (b ) == 4 && string (b ) == "\" {}\" "
30+ if isEmptyResponse {
31+ return nil
32+ }
33+
34+ // new type prevents recursive calls to RedditResponse.UnmarshalJSON()
35+ type resp * RedditResponse
36+ return json .Unmarshal (b , resp (r ))
37+ }
38+
2639// SearchReddit searches Reddit for given query and returns list of discussions
2740// sorted by relevance.
2841//
Original file line number Diff line number Diff line change @@ -18,3 +18,14 @@ func ExampleSearchReddit() {
1818 // Output:
1919 // Reddit https://reddit.com/r/hypeurls/comments/17k6i1l/the_grug_brained_developer_2022/ The Grug Brained Developer (2022) https://grugbrain.dev/
2020}
21+
22+ func ExampleSearchReddit_unknown () {
23+ client := http.Client {}
24+ query := "https://invalid.domain/query"
25+
26+ opinions := ensure .MustReturn (SearchReddit (context .TODO (), client , query ))
27+
28+ fmt .Println (len (opinions ))
29+ // Output:
30+ // 0
31+ }
You can’t perform that action at this time.
0 commit comments