Last active
August 29, 2015 14:01
-
-
Save smtalim/7082d3c786b0b20ab035 to your computer and use it in GitHub Desktop.
Third Iteration
This file contains hidden or 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 main | |
import ( | |
"encoding/json" | |
"errors" | |
"fmt" | |
"log" | |
"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) | |
} | |
func main() { | |
items, err := Get("golang") | |
if err != nil { | |
log.Fatal(err) | |
} | |
for _, item := range items { | |
fmt.Println(item) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment