github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2012/tutorial/reddit/reddit.go (about)

     1  // Package reddit implements a basic client for the Reddit API.
     2  // +build OMIT
     3  
     4  package reddit
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"net/http"
    10  )
    11  
    12  // Item describes a Reddit item.
    13  type Item struct {
    14  	Title    string
    15  	URL      string
    16  	Comments int `json:"num_comments"`
    17  }
    18  
    19  func (i Item) String() string {
    20  	com := ""
    21  	switch i.Comments {
    22  	case 0:
    23  		// nothing
    24  	case 1:
    25  		com = " (1 comment)"
    26  	default:
    27  		com = fmt.Sprintf(" (%d comments)", i.Comments)
    28  	}
    29  	return fmt.Sprintf("%s%s\n%s", i.Title, com, i.URL)
    30  }
    31  
    32  // Get fetches the most recent Items posted to the specified subreddit.
    33  func Get(reddit string) ([]Item, error) {
    34  	url := fmt.Sprintf("http://reddit.com/r/%s.json", reddit)
    35  	resp, err := http.Get(url)
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	defer resp.Body.Close()
    40  	if resp.StatusCode != http.StatusOK {
    41  		return nil, errors.New(resp.Status)
    42  	}
    43  	r := new(response)
    44  	err = json.NewDecoder(resp.Body).Decode(r)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	items := make([]Item, len(r.Data.Children))
    49  	for i, child := range r.Data.Children {
    50  		items[i] = child.Data
    51  	}
    52  	return items, nil
    53  }
    54  
    55  type response struct {
    56  	Data struct {
    57  		Children []struct {
    58  			Data Item
    59  		}
    60  	}
    61  }