-
Notifications
You must be signed in to change notification settings - Fork 0
/
onionreq.go
74 lines (68 loc) · 1.51 KB
/
onionreq.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
package requests
import (
"bytes"
"fmt"
"golang.org/x/net/proxy"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
)
func fatalf(fmtStr string, args interface{}) {
fmt.Fprintf(os.Stderr, fmtStr, args)
os.Exit(-1)
}
// ReqHandler unsurprisingly handles requests
type ReqHandler struct {
Header http.Header
client http.Client
}
// Constructor
func NewHandler(headers http.Header) (*ReqHandler, error) {
tbProxyURL, err := url.Parse("socks5://127.0.0.1:9050")
if err != nil {
return nil, err
}
tbDialer, err := proxy.FromURL(tbProxyURL, proxy.Direct)
if err != nil {
return nil, err
}
tr := &http.Transport{Dial: tbDialer.Dial}
client := http.Client{Transport: tr}
r := &ReqHandler{Header: headers, client: client}
return r, nil
}
// Do runs the requests and returns the response object
func (r *ReqHandler) Do(method, url string, data *string, header *http.Header) (*http.Response, error) {
var buf io.Reader
if data != nil {
buf = bytes.NewBufferString(*data)
}
req, err := http.NewRequest(method, url, buf)
if err != nil {
return nil, err
}
if header != nil {
req.Header = *header
} else {
req.Header = r.Header
}
res, err := r.client.Do(req)
if err != nil {
return nil, err
}
return res, nil
}
func (r *ReqHandler) Request(method, url string, data *string, header *http.Header) ([]byte, error) {
res, err := r.Do(method, url, data, header)
if err != nil {
return nil, err
}
defer res.Body.Close()
content, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
return content, nil
}