Skip to content

Instantly share code, notes, and snippets.

@smtalim
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smtalim/248c2f777941e31b2319 to your computer and use it in GitHub Desktop.
Save smtalim/248c2f777941e31b2319 to your computer and use it in GitHub Desktop.
Fourth Iteration
package redditnews
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
type Item struct {
Author string `json:"author"`
Score int `json:"score"`
URL string `json:"url"`
Title string `json:"title"`
}
type response struct {
Data1 struct {
Children []struct {
Data2 Item `json:"data"`
} `json:"children"`
} `json:"data"`
}
func Get(reddit string) ([]Item, error) {
url := fmt.Sprintf("http://reddit.com/r/%s.json", reddit)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
r := new(response)
err = json.NewDecoder(resp.Body).Decode(r)
if err != nil {
return nil, err
}
items := make([]Item, len(r.Data1.Children))
for i, child := range r.Data1.Children {
items[i] = child.Data2
}
return items, nil
}
func (i Item) String() string {
return fmt.Sprintf(
"Author: %s\nScore: %d\nURL: %s\nTitle: %s\n\n",
i.Author,
i.Score,
i.URL,
i.Title)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment