Created
May 19, 2014 08:41
-
-
Save smtalim/66d3d64959b55866a41a 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 redditnews | |
import ( | |
"bytes" | |
"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 Email() string { | |
var buffer bytes.Buffer | |
items, err := Get("golang") | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Need to build strings from items | |
for _, item := range items { | |
buffer.WriteString(item.String()) | |
} | |
return buffer.String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment