Last active
December 13, 2015 20:19
-
-
Save jameshwang/4969259 to your computer and use it in GitHub Desktop.
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 main | |
import ( | |
"encoding/json" | |
"errors" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
type Item struct { | |
Title string | |
URL string | |
Comments int `json:"num_comments"` | |
} | |
type Response struct { | |
Data struct { | |
Children []struct { | |
Data Item | |
} | |
} | |
} | |
func (i Item) String() string { | |
com := "" | |
switch i.Comments { | |
case 0: | |
// Nothing | |
case 1: | |
com = " (1 comment)" | |
default: | |
com = fmt.Sprintf(" (%d comments)", i.Comments) | |
} | |
return fmt.Sprintf("%s%s\n%s", i.Title, com, i.URL) | |
} | |
func main() { | |
items, err := Get("golang") | |
if err != nil { | |
log.Fatal(err) | |
} | |
for _, item := range items { | |
fmt.Println(item.String()) | |
} | |
} | |
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.Data.Children)) | |
for i, child := range r.Data.Children { | |
items[i] = child.Data | |
} | |
return items, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment