Documentation ¶
Overview ¶
Package reddit provides wrappers to the Reddit API for Go.
Please read the reddit API documentation first before reading these docs. Some useful links are:
- https://github.com/reddit/reddit/wiki/API
- https://github.com/reddit/reddit/wiki/JSON
- https://github.com/reddit/reddit/wiki/OAuth2-Quick-Start-Example
- https://github.com/reddit/reddit/wiki/OAuth2
- https://www.reddit.com/dev/api
This currently only supports OAuth for script apps. It does not support refreshing OAuth tokens. It provides the following:
- Code to save and load authorization credentials (client id, client secret, etc).
- A simple API to obtain and store an OAuth token for a script app using these credentials.
- An API to perform GET requests using the obtained token.
- An API to stream listings.
Please see the package examples for details on how to use the above functionality.
Index ¶
Examples ¶
Constants ¶
const ( // RedditAuthURL is the URL used to obtain an authentication token. RedditAuthURL = "https://www.reddit.com/api/v1/access_token" // RedditAPIURL is the base URL used to make API calls. RedditAPIURL = "https://oauth.reddit.com" // DefaultConfigFile is the default file used to store API credentials. DefaultConfigFile = "~/.reddit_creds" )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Account ¶
type Account struct { Created CommentKarma int `json:"comment_karma"` HasMail bool `json:"has_mail"` HasModMail bool `json:"has_mod_mail"` HasVerifiedEmail bool `json:"has_verified_email"` ID string `json:"id"` InboxCount int `json:"inbox_count"` IsFriend bool `json:"is_friend"` IsGold bool `json:"is_gold"` IsMod bool `json:"is_mod"` LinkKarma int `json:"link_karma"` Modhash string `json:"modhash"` Name string `json:"name"` Over18 bool `json:"over_18"` }
Account represents a single account on reddit.
type AuthToken ¶
type AuthToken struct { Expires int64 `json:"expires"` // Expirations time as seconds since the unix epoch Token string `json:"token"` // OAuth token Type string `json:"type"` // Type of token (usually just bearer) }
AuthToken contains an authentication token obtained via OAuth.
type Comment ¶
type Comment struct { Votable Created ApprovedBy string `json:"approved_by"` Author string `json:"author"` AuthorFlairCSSClass string `json:"author_flair_css_class"` AuthorFlairText string `json:"author_flair_text"` BannedBy string `json:"banned_by"` Body string `json:"body"` BodyHTML string `json:"body_html"` Edited Edited `json:"edited"` Gilded int `json:"gilded"` Likes bool `json:"likes"` LinkAuthor string `json:"link_author"` LinkID string `json:"link_id"` LinkTitle string `json:"link_title"` LinkURL string `json:"link_url"` NumReports int `json:"num_reports"` ParentID string `json:"parent_id"` Replies []Thing `json:"replies"` Saved bool `json:"saved"` Score int `json:"score"` ScoreHidden bool `json:"score_hidden"` Subreddit string `json:"subreddit"` SubredditID string `json:"subreddit_id"` Distinguished string `json:"distinguished"` }
Comment represents a single reddit comment.
type Config ¶
type Config struct { Credentials Credentials `json:"credentials"` AuthToken AuthToken `json:"token"` }
Config contains configuration needed to perform reddit API requests. This consists of credentials used to obtain a token and the current token. The credentials must be provided by the user of this library. Calling AuthScript then authenticates the client and populates the AuthToken.
func LoadConfig ¶
LoadConfig loads and validates a Config structure stored as JSON from a configuration file. If the file path starts with ~ this is expanded to the home directory of the user. All fields in the Credentials field must be non-empty.
func (*Config) AuthScript ¶
AuthScript authenticates the client against reddit's API servers using the method described in https://github.com/reddit/reddit/wiki/OAuth2-Quick-Start-Example. If Config.AuthToken holds a valid token, no authentication is performed.
If authentication is successful Config.AuthToken is populated with the received authentication token. Use Config.Save to save this authentication token.
func (*Config) Get ¶
Get performs an authentication GET request to the provided URL using the provided http.Client instance. Responses are unmarshalled into val.
func (*Config) Save ¶
Save saves a config in JSON format to the provided file. If the file path starts with ~ this is expanded to the home directory of the user. No validation is performed on the Config prior to saving.
func (*Config) Stream ¶
Stream returns a Stream that pages through a Listing. The provided lister is automatically updated to hold the correct After and Count values for paging. All requests are performed using the provided http.Client instance.
Example ¶
cfg, err := reddit.LoadConfig(reddit.DefaultConfigFile) if err != nil { log.Fatal(err) } if err := cfg.AuthScript(http.DefaultClient); err != nil { log.Fatal(err) } // Print top posts of the day from /r/golang stream := cfg.Stream(http.DefaultClient, &reddit.TopPosts{SubReddit: "golang", Duration: reddit.TopDay}) for stream.Next() { thing := stream.Thing() link := thing.Data.(*reddit.Link) fmt.Println(link.Title, link.URL) } if err := stream.Error(); err != nil { log.Fatal(err) }
Output:
type Credentials ¶
type Credentials struct { Username string `json:"username"` // Reddit username of the developer account. Password string `json:"password"` // Password for the above user. ClientID string `json:"clientID"` // Client ID for the script app. ClientSecret string `json:"client_secret"` // Client secret for the script app. UserAgent string `json:"user_agent"` // User Agent to use when making requests. }
Credentials contains script credentials for a reddit developer account.
type Edited ¶
Edited denotes the current edit state of a Thing. If Edited is true, Unix will hold the last edited time as seconds since the unix epoch.
func (*Edited) MarshalJSON ¶
MarshalJSON implements json.Marshaler for Edited. It returns false if e.Edited is false and a float timestamp if not.
func (*Edited) UnmarshalJSON ¶
UnmarshalJSON implement json.Unmarshaller for Edited. It expects false if no edits were performed, or a float timestamp of when the last edit was performed.
type HeaderSize ¶
HeaderSize is a header size for a subreddit.
func (*HeaderSize) MarshalJSON ¶
func (h *HeaderSize) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for HeaderSize. It converts HeaderSize into an array of ints.
func (*HeaderSize) UnmarshalJSON ¶
func (h *HeaderSize) UnmarshalJSON(b []byte) error
UnmarshalJSON implements json.Unmarshaler for HeaderSize. It converts an array of ints into a HeaderSize.
type Link ¶
type Link struct { Votable Created Author string `json:"author"` AuthorFlairCSSClass string `json:"author_flair_css_class"` AuthorFlairText string `json:"author_flair_text"` Clicked bool `json:"clicked"` Domain string `json:"domain"` Hidden bool `json:"hidden"` IsSelf bool `json:"is_self"` Likes bool `json:"likes"` LinkFlairCSSClass string `json:"link_flair_css_class"` LinkFlairText string `json:"link_flair_text"` Locked bool `json:"locked"` Media json.RawMessage `json:"media"` MediaEmbed json.RawMessage `json:"media_embed"` NumComments int `json:"num_comments"` Over18 bool `json:"over_18"` Permalink string `json:"permalink"` Saved bool `json:"saved"` Score int `json:"score"` Selftext string `json:"selftext"` SelftextHTML string `json:"selftext_html"` Subreddit string `json:"subreddit"` SubredditID string `json:"subreddit_id"` Thumbnail string `json:"thumbnail"` Title string `json:"title"` URL string `json:"url"` Edited Edited `json:"edited"` Distinguished string `json:"distinguished"` Stickied bool `json:"stickied"` }
Link represents a single link on reddit.
type Lister ¶
type Lister interface { URLer List() *ListingOptions }
Lister provides access to a modifiable ListingOptions instance which is used to stream Listings.
type Listing ¶
type Listing struct { Before string `json:"before"` After string `json:"after"` Modhash string `json:"modhash"` Children []Thing `json:"children"` }
Listing contains paginated content from an API request.
type ListingOptions ¶
type ListingOptions struct { After string `url:"after,omitempty"` Before string `url:"before,omitempty"` Count int `url:"count,omitempty"` Limit int `url:"limit,omitempty"` Show string `url:"show,omitempty"` }
ListingOptions control the size and position of a streamed listing. See https://www.reddit.com/dev/api for more information on what these parameters mean.
type Message ¶
type Message struct { Created Author string `json:"author"` Body string `json:"body"` BodyHTML string `json:"body_html"` Context string `json:"context"` FirstMessage string `json:"first_message"` FirstMessageName string `json:"first_message_name"` Likes bool `json:"likes"` LinkTitle string `json:"link_title"` Name string `json:"name"` New bool `json:"new"` ParentID string `json:"parent_id"` Replies string `json:"replies"` Subject string `json:"subject"` Subreddit string `json:"subreddit"` WasComment bool `json:"was_comment"` }
Message represents a single message on reddit.
type More ¶
type More struct {
Children []string `json:"children"`
}
More holds a list of Thing IDs that are present but not included in full in a response.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream represents a stream of Thing values obtained from a Listing url.
func (*Stream) Error ¶
Error returns a non-nil error if there were any errors when fetching the listing.
type SubReddit ¶
type SubReddit struct { AccountsActive int `json:"accounts_active"` CommentScoreHideMins int `json:"comment_score_hide_mins"` Description string `json:"description"` DescriptionHTML string `json:"description_html"` DisplayName string `json:"display_name"` HeaderImg string `json:"header_img"` HeaderSize *HeaderSize `json:"header_size"` HeaderTitle string `json:"header_title"` Over18 bool `json:"over18"` PublicDescription string `json:"public_description"` PublicTraffic bool `json:"public_traffic"` Subscribers int64 `json:"subscribers"` SubmissionType string `json:"submission_type"` SubmitLinkLabel string `json:"submit_link_label"` SubmitTextLabel string `json:"submit_text_label"` SubredditType string `json:"subreddit_type"` Title string `json:"title"` URL string `json:"url"` UserIsBanned bool `json:"user_is_banned"` UserIsContributor bool `json:"user_is_contributor"` UserIsModerator bool `json:"user_is_moderator"` UserIsSubscriber bool `json:"user_is_subscriber"` }
SubReddit represents a single subreddit.
type Thing ¶
type Thing struct { ID string `json:"id"` Name string `json:"name"` Kind string `json:"kind"` Data interface{} `json:"data"` }
Thing holds attributes common to all reddit api entities.
See https://github.com/reddit/reddit/wiki/JSON
func (*Thing) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaller for Thing. It performs this in two passes. In the first pass the data is left unmarshalled. The value of kind is then used to determine the struct type for Data.
type TopDuration ¶
type TopDuration string
TopDuration represents a sort value for fetching top posts.
const ( TopHour TopDuration = "hour" TopDay TopDuration = "day" TopWeek TopDuration = "week" TopMonth TopDuration = "month" TopYear TopDuration = "year" TopAll TopDuration = "all" )
TopHour, TopDay, TopWeek, TopMonth, TopYear and TopAll are supported sort values for a TopPosts request.
type TopPosts ¶
type TopPosts struct { ListingOptions SubReddit string `url:"-"` Duration TopDuration `url:"t,omitempty"` }
TopPosts is a query for the top posts of a specified subreddit. It implements URLer and Lister and can be used with Config.Stream to stream the top posts of a subreddit.
func (*TopPosts) List ¶
func (t *TopPosts) List() *ListingOptions
List returns the ListingOptions for TopPosts