Skip to content

Instantly share code, notes, and snippets.

@xiam
Created January 6, 2014 13:36
Show Gist options
  • Save xiam/8282977 to your computer and use it in GitHub Desktop.
Save xiam/8282977 to your computer and use it in GitHub Desktop.
An example file for using reddit API with Go.
package main
import (
"fmt"
"menteslibres.net/gosexy/rest"
"menteslibres.net/gosexy/to"
"net/url"
"time"
)
type RedditResponse struct {
Data struct {
Children []struct {
Data Post `json:"data"`
} `json:"children"`
} `json:"data"`
}
type Post struct {
Thumbnail string `json:"thumbnail"`
Ups uint `json:"ups"`
Downs uint `json:"downs"`
Url string `json:"url"`
Title string `json:"title"`
CreatedUTC Time `json:"created_utc"`
}
type Time struct {
time.Time
}
func (self *Time) UnmarshalJSON(data []byte) error {
// Time values are returned like 123456789.0, that does not unmarshal nicely
// into a float, integer nor a time.Time, so we had to unmarshal it by
// wrapping time.Time and adding a custom unmarshaler.
self.Time = time.Unix(0, 0).UTC()
self.Time = self.Time.Add(to.Duration(string(data) + "s"))
return nil
}
func main() {
var err error
data := RedditResponse{}
err = rest.Get(&data, "http://www.reddit.com/r/pics.json", url.Values{"limit": {"100"}})
if err == nil {
for _, child := range data.Data.Children {
fmt.Println("Title: ", child.Data.Title, "(ups: ", child.Data.Ups, ", downs: ", child.Data.Downs, ")")
fmt.Println("URL: ", child.Data.Url)
fmt.Printf("Date: %v\n", child.Data.CreatedUTC)
fmt.Println("--")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment