-
Notifications
You must be signed in to change notification settings - Fork 1
/
uploadFile.go
84 lines (65 loc) Β· 1.5 KB
/
uploadFile.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
package api
import (
"bytes"
"context"
"encoding/json"
"io"
"mime/multipart"
"net/http"
)
func get(link string) (data []byte, err error) {
request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, link, nil)
if err != nil {
return nil, err
}
response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, err
}
if err := response.Body.Close(); err != nil {
return nil, err
}
body, err := io.ReadAll(response.Body)
data = body
return
}
type UploadFile []byte
func (bot *Bot) UploadFile(serverURL, fileURL, field, name string) (uploadedFile UploadFile, err error) {
body := new(bytes.Buffer)
write := multipart.NewWriter(body)
part, err := write.CreateFormFile(field, name)
if err != nil {
return nil, err
}
file, err := get(fileURL)
if err != nil {
return nil, err
}
_, err = io.Copy(part, bytes.NewReader(file))
if err != nil {
return nil, err
}
contentType := write.FormDataContentType()
_ = write.Close()
request, err := http.NewRequestWithContext(context.Background(), "POST", serverURL, body)
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", contentType)
response, err := bot.Bot.HTTPClient.Do(request)
if err != nil {
err := response.Body.Close()
if err != nil {
return nil, err
}
return nil, err
}
content, readErr := io.ReadAll(response.Body)
if readErr != nil {
return nil, err
}
return content, nil
}
func (file UploadFile) JSON(data any) error {
return json.Unmarshal(file, data)
}