-
Notifications
You must be signed in to change notification settings - Fork 2
/
request.go
125 lines (85 loc) · 2.3 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package telepher
import (
"net/http"
"net/url"
"mime/multipart"
"io/ioutil"
"io"
"bytes"
"fmt"
"os"
"github.com/goTelegramBot/telepher/types"
"encoding/json"
)
type apiResponse struct {
OK bool `json:"ok"`
Result json.RawMessage `json:"result"`
Description string `json:"description"`
ErrorCode int `json:"error_code"`
Parameters *types.ResponseParameters `json:"parameters"`
}
func (telepher Bot) post(endpoint string, params url.Values )(json.RawMessage ,error){
var resp *http.Response
var err error
URL := telepher.BaseURL + telepher.Token + "/" + endpoint
if params == nil {
resp, err = http.Post(URL, "application/x-www-form-urlencoded", nil)
} else {
resp, err = http.PostForm(URL,params)
}
if err != nil {
return nil,err
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil , err
}
var response apiResponse
if err := json.Unmarshal(data,&response); err != nil {
return nil, err
}
if !response.OK{
fmt.Println(response)
return nil , fmt.Errorf("telepher : api error %s : %d", response.Description, response.ErrorCode)
}
return response.Result ,nil
}
func (telepher Bot) postWithFile(endpoint string ,filetype string,path string, params url.Values)(json.RawMessage ,error){
URL := telepher.BaseURL + telepher.Token + "/" + endpoint
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
File, err := os.Open(path)
if err != nil {
return nil, err
}
part, err := writer.CreateFormFile(filetype, path)
if err != nil {
return nil, err
}
_, err = io.Copy(part, File)
for key:= range params {
_ = writer.WriteField(key,params.Get(key))
}
err = writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", URL, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
if err != nil {
return nil,err
}
resp, err := telepher.Client.Do(req)
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil , err
}
var response apiResponse
if err := json.Unmarshal(data,&response); err != nil {
return nil, err
}
if !response.OK{
return nil , fmt.Errorf("telepher : api error %d : %s", response.ErrorCode, response.Description)
}
return response.Result ,nil
}