-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegraph.go
75 lines (61 loc) · 1.81 KB
/
telegraph.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
package telegraph
import (
"encoding/json"
"errors"
jsoniter "github.com/json-iterator/go"
http "github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpproxy"
)
// Response contains a JSON object, which always has a Boolean field ok. If ok equals true, the request was
// successful, and the result of the query can be found in the result field. In case of an unsuccessful request, ok
// equals false, and the error is explained in the error field (e.g. SHORT_NAME_REQUIRED).
type Response struct {
Ok bool `json:"ok"`
Error string `json:"error,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
}
var parser = jsoniter.ConfigFastest //nolint:gochecknoglobals
var c = &http.Client{}
// "localhost:9050"
func SetSocksDialer(proxy string) {
c = &http.Client{
Dial: fasthttpproxy.FasthttpSocksDialer(proxy),
}
}
// "username:password@localhost:9050"
func SetHttpDialer(proxy string) {
c = &http.Client{
Dial: fasthttpproxy.FasthttpHTTPDialer(proxy),
}
}
func makeRequest(path string, payload interface{}) ([]byte, error) {
src, err := parser.Marshal(payload)
if err != nil {
return nil, err
}
u := http.AcquireURI()
defer http.ReleaseURI(u)
u.SetScheme("https")
u.SetHost("api.telegra.ph")
u.SetPath(path)
req := http.AcquireRequest()
defer http.ReleaseRequest(req)
req.SetRequestURIBytes(u.FullURI())
req.Header.SetMethod(http.MethodPost)
req.Header.SetUserAgent("toby3d/telegraph")
req.Header.SetContentType("application/json")
req.SetBody(src)
resp := http.AcquireResponse()
defer http.ReleaseResponse(resp)
if err := c.Do(req, resp); err != nil {
return nil, err
}
r := new(Response)
if err := parser.Unmarshal(resp.Body(), r); err != nil {
return nil, err
}
if !r.Ok {
return nil, errors.New(r.Error) //nolint: goerr113
}
return r.Result, nil
}