Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

initial commit

commit 84a1132cd8a32ed4ee490ecc753c334ac302f99c 0 parents
@nf authored
Showing with 74 additions and 0 deletions.
  1. +17 −0 geddit/main.go
  2. +57 −0 reddit.go
17 geddit/main.go
@@ -0,0 +1,17 @@
+package main
+
+import (
+ "fmt"
+ "log"
+ "github.com/nf/reddit"
+)
+
+func main() {
+ items, err := reddit.Get("golang")
+ if err != nil {
+ log.Fatal(err)
+ }
+ for _, item := range items {
+ fmt.Println(item)
+ }
+}
57 reddit.go
@@ -0,0 +1,57 @@
+package reddit
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+)
+
+type Response struct {
+ Data struct {
+ Children []struct {
+ Data Item
+ }
+ }
+}
+
+type Item struct {
+ Title string
+ URL string
+ Comments int `json:"num_comments"`
+}
+
+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 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
+}
Please sign in to comment.
Something went wrong with that request. Please try again.