-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmisc.go
52 lines (42 loc) · 1.09 KB
/
misc.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
package bot
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"os"
)
func generateContentType(params map[string]string, files map[string]string, custom_byte *bytes.Buffer) (string, error) {
writer := multipart.NewWriter(custom_byte)
for key, value := range params {
writer.WriteField(key, value)
}
if len(files) > 0 {
for key, value := range files {
writeMultipart(value, writer, key)
}
}
err := writer.Close()
return writer.FormDataContentType(), err
}
func writeMultipart(path string, writer *multipart.Writer, key string) error {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
fileContent, err := io.ReadAll(file)
if err != nil {
return fmt.Errorf("failed to read file content: %w", err)
}
fi, err := file.Stat()
if err != nil {
return fmt.Errorf("failed to get file content: %w", err)
}
file.Close()
part, err := writer.CreateFormFile(key, fi.Name())
if err != nil {
return fmt.Errorf("failed to create multipart form: %w", err)
}
part.Write(fileContent)
return err
}