diff --git a/reddit.go b/reddit.go index 0adfebe..a5a6ee4 100644 --- a/reddit.go +++ b/reddit.go @@ -23,6 +23,19 @@ type RedditResponse struct { } `json:"data"` } +// UnmarshalJSON deserialize inconsistent JSON responses to RedditResponse. +// Reddit returns empty object ("{}") when there are no search results. +func (r *RedditResponse) UnmarshalJSON(b []byte) error { + isEmptyResponse := len(b) == 4 && string(b) == "\"{}\"" + if isEmptyResponse { + return nil + } + + // new type prevents recursive calls to RedditResponse.UnmarshalJSON() + type resp *RedditResponse + return json.Unmarshal(b, resp(r)) +} + // SearchReddit searches Reddit for given query and returns list of discussions // sorted by relevance. // diff --git a/reddit_test.go b/reddit_test.go index d172ef7..edc7cc0 100644 --- a/reddit_test.go +++ b/reddit_test.go @@ -18,3 +18,14 @@ func ExampleSearchReddit() { // Output: // Reddit https://reddit.com/r/hypeurls/comments/17k6i1l/the_grug_brained_developer_2022/ The Grug Brained Developer (2022) https://grugbrain.dev/ } + +func ExampleSearchReddit_unknown() { + client := http.Client{} + query := "https://invalid.domain/query" + + opinions := ensure.MustReturn(SearchReddit(context.TODO(), client, query)) + + fmt.Println(len(opinions)) + // Output: + // 0 +}