-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest.go
89 lines (70 loc) · 1.9 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
package telegram
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/technoweenie/multipartstreamer"
)
const requestAddress = "https://api.telegram.org"
type RequestHandler func(methodName string, req interface{}) (json.RawMessage, error)
type Response struct {
Ok bool `json:"ok"`
Result json.RawMessage `json:"result"`
ErrorCode int `json:"error_code"`
Description string `json:"description"`
Parameters *ResponseParameters `json:"parameters"`
}
type ErrorResponse Response
func (e ErrorResponse) Error() string {
return fmt.Sprintf("resp not ok, descr=%v, code=%v", e.Description, e.ErrorCode)
}
func (b *Bot) executeRequest(methodName string, req interface{}) (json.RawMessage, error) {
url := fmt.Sprintf("%s/bot%s/%s", requestAddress, b.token, methodName)
var httpReq *http.Request
if upload, ok := isFileUpload(req); ok {
if upload.err != nil {
return nil, upload.err
}
ms := multipartstreamer.New()
ms.WriteFields(upload.params)
r, err := upload.file.Reader()
if err != nil {
return nil, err
}
ms.WriteReader(upload.fieldname, upload.file.Name(), upload.file.Size(), r)
if rc, ok := r.(io.ReadCloser); ok {
defer rc.Close()
}
httpReq, err = http.NewRequest("POST", url, nil)
if err != nil {
return nil, err
}
ms.SetupRequest(httpReq)
} else {
body, err := json.Marshal(req)
if err != nil {
return nil, err
}
httpReq, err = http.NewRequest("POST", url, bytes.NewReader(body))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", "application/json")
}
resp, err := b.client.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var respObj Response
err = json.NewDecoder(resp.Body).Decode(&respObj)
if err != nil {
return nil, err
}
if !respObj.Ok {
return nil, ErrorResponse(respObj)
}
return respObj.Result, nil
}