-
Notifications
You must be signed in to change notification settings - Fork 3
/
02-http.go
90 lines (79 loc) · 2.21 KB
/
02-http.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
package quitter
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// fireGET sends a get request and returns byte, error.
func (a Account) fireGET(path string) ([]byte, error) {
if path == "" {
return nil, errors.New("No path")
}
apipath := a.Scheme + a.Node + path
req, err := http.NewRequest("GET", apipath, nil)
req.Header.Set("User-Agent", UserAgent)
req.SetBasicAuth(a.Username, a.Password)
if err != nil {
return nil, err
}
var resp *http.Response
resp, err = apigun.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if string(body) == "" {
return nil, errors.New("node response: " + resp.Status)
}
/*
Here, I tried a couple ways of telling if the response was an error.
This one ended up working the most reliably. TODO:
*/
var apiresponse Badrequest
_ = json.Unmarshal(body, &apiresponse)
if apiresponse.Error != "" {
return nil, errors.New(apiresponse.Error)
}
return body, nil
}
// firePOST uses the account details to send a POST request to the node.
// HTTP_REFERER is added to keep nodes happy.
func (a Account) firePOST(path string, v url.Values) ([]byte, error) {
if path == "" {
return nil, errors.New("No path")
}
if v.Encode() == "" && !strings.Contains(path, "update") { // update can use a blank post request..
return nil, errors.New("No values to post")
}
apipath := a.Scheme + a.Node + path
b := bytes.NewBufferString(v.Encode())
req, err := http.NewRequest("POST", apipath, b)
if err != nil {
return nil, err
}
req.SetBasicAuth(a.Username, a.Password)
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("HTTP_REFERER", a.Scheme+a.Node+"/")
// req.Header.Add("Content-Type", "[application/json; charset=utf-8") // is this a typo ?
var resp *http.Response
resp, err = apigun.Do(req)
if err != nil {
return nil, err
}
body, _ := ioutil.ReadAll(resp.Body)
if string(body) == "" {
return nil, errors.New("node response: " + resp.Status)
}
var apiresponse Badrequest
_ = json.Unmarshal(body, &apiresponse)
if apiresponse.Error != "" {
return nil, errors.New(apiresponse.Error)
}
return body, nil
}