forked from ahmdrz/goinsta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
115 lines (96 loc) · 2.35 KB
/
request.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
107
108
109
110
111
112
113
114
115
package goinsta
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type reqOptions struct {
Endpoint string
PostData string
IsLoggedIn bool
IgnoreStatus bool
Query map[string]string
}
func (insta *Instagram) OptionalRequest(endpoint string, a ...interface{}) (body []byte, err error) {
return insta.sendRequest(&reqOptions{
Endpoint: fmt.Sprintf(endpoint, a...),
})
}
func (insta *Instagram) sendSimpleRequest(endpoint string, a ...interface{}) (body []byte, err error) {
return insta.sendRequest(&reqOptions{
Endpoint: fmt.Sprintf(endpoint, a...),
})
}
func (insta *Instagram) sendRequest(o *reqOptions) (body []byte, err error) {
if !insta.IsLoggedIn && !o.IsLoggedIn {
return nil, fmt.Errorf("not logged in")
}
method := "GET"
if len(o.PostData) > 0 {
method = "POST"
}
u, err := url.Parse(GOINSTA_API_URL + o.Endpoint)
if err != nil {
return nil, err
}
q := u.Query()
for k, v := range o.Query {
q.Add(k, v)
}
u.RawQuery = q.Encode()
var req *http.Request
req, err = http.NewRequest(method, u.String(), bytes.NewBuffer([]byte(o.PostData)))
if err != nil {
return
}
req.Header.Set("Connection", "close")
req.Header.Set("Accept", "*/*")
req.Header.Set("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("Cookie2", "$Version=1")
req.Header.Set("Accept-Language", "en-US")
req.Header.Set("User-Agent", GOINSTA_USER_AGENT)
client := &http.Client{
Jar: insta.Cookiejar,
}
if insta.Proxy != "" {
proxy, err := url.Parse(insta.Proxy)
if err != nil {
return body, err
}
insta.Transport.Proxy = http.ProxyURL(proxy)
client.Transport = &insta.Transport
} else {
// Remove proxy if insta.Proxy was removed
insta.Transport.Proxy = nil
client.Transport = &insta.Transport
}
resp, err := client.Do(req)
if err != nil {
return body, err
}
defer resp.Body.Close()
u, _ = url.Parse(GOINSTA_API_URL)
for _, value := range insta.Cookiejar.Cookies(u) {
if strings.Contains(value.Name, "csrftoken") {
insta.Informations.Token = value.Value
}
}
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if resp.StatusCode != 200 && !o.IgnoreStatus {
e := fmt.Errorf("Invalid status code %s", string(body))
switch resp.StatusCode {
case 400:
e = ErrLoggedOut
case 404:
e = ErrNotFound
}
return nil, e
}
return body, err
}