-
Notifications
You must be signed in to change notification settings - Fork 6
/
requests.go
44 lines (38 loc) · 1.16 KB
/
requests.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
package telegraph
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
)
type Body struct {
// Ok: if true, request was successful, and result can be found in the Result field.
// If false, error can be explained in Error field.
Ok bool `json:"ok"`
// Error: contains a human-readable description of the error result.
Error string `json:"error"`
// Result: result of requests (if Ok)
Result json.RawMessage `json:"result"`
}
func (c *TelegraphClient) InvokeRequest(method string, params url.Values) (json.RawMessage, error) {
r, err := http.NewRequest(http.MethodPost, c.ApiUrl+method, strings.NewReader(params.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to build POST request to %s: %w", method, err)
}
resp, err := c.HttpClient.Do(r)
if err != nil {
return nil, fmt.Errorf("failed to execute POST request to %s: %w", method, err)
}
defer func() {
_ = resp.Body.Close()
}()
var b Body
if err = json.NewDecoder(resp.Body).Decode(&b); err != nil {
return nil, fmt.Errorf("failed to parse response from %s: %w", method, err)
}
if !b.Ok {
return nil, fmt.Errorf("failed to %s: %s", method, b.Error)
}
return b.Result, nil
}