-
Notifications
You must be signed in to change notification settings - Fork 12
/
reddit.go
106 lines (87 loc) · 2.57 KB
/
reddit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Package reddit provides Reddit API wrapper utilities.
package reddit
import (
"bytes"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
)
const (
baseAuthURL = "https://oauth.reddit.com"
baseURL = "http://reddit.com"
)
// Client is the client for interacting with the Reddit API.
type Client struct {
http *http.Client
userAgent string
}
// NoAuthClient is the unauthenticated client for interacting with the Reddit API.
var NoAuthClient = &Client{
http: new(http.Client),
}
func (c *Client) commentOnThing(fullname string, text string) error {
data := url.Values{}
data.Set("thing_id", fullname)
data.Set("text", text)
data.Set("api_type", "json")
url := fmt.Sprintf("%s/api/comment", baseAuthURL)
req, err := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))
if err != nil {
return err
}
req.Header.Add("User-Agent", c.userAgent)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, err := c.http.Do(req)
if err != nil {
return err
} else if resp.StatusCode >= 400 {
return errors.New(fmt.Sprintf("HTTP Status Code: %d", resp.StatusCode))
}
defer resp.Body.Close()
return nil
}
func (c *Client) deleteThing(fullname string) error {
data := url.Values{}
data.Set("id", fullname)
url := fmt.Sprintf("%s/api/del", baseAuthURL)
req, err := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))
if err != nil {
return err
}
req.Header.Add("User-Agent", c.userAgent)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, err := c.http.Do(req)
if err != nil {
return err
} else if resp.StatusCode >= 400 {
return errors.New(fmt.Sprintf("HTTP Status Code: %d", resp.StatusCode))
}
defer resp.Body.Close()
return nil
}
func (c *Client) editThingText(fullname string, text string) error {
data := url.Values{}
data.Set("thing_id", fullname)
data.Set("text", text)
data.Set("api_type", "json")
url := fmt.Sprintf("%s/api/editusertext", baseAuthURL)
req, err := http.NewRequest("POST", url, bytes.NewBufferString(data.Encode()))
if err != nil {
return err
}
req.Header.Add("User-Agent", c.userAgent)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, err := c.http.Do(req)
if err != nil {
return err
} else if resp.StatusCode >= 400 {
return errors.New(fmt.Sprintf("HTTP Status Code: %d", resp.StatusCode))
}
defer resp.Body.Close()
return nil
}