Last active
August 29, 2015 14:01
-
-
Save smtalim/248c2f777941e31b2319 to your computer and use it in GitHub Desktop.
Fourth Iteration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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