-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathform_factory.go
61 lines (50 loc) · 1.24 KB
/
form_factory.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
package openai
import (
"io"
"mime/multipart"
"os"
"github.com/pkg/errors"
)
type FormFactory interface {
CreateFormFile(fieldname string, filepath string) error
WriteField(fieldname string, value string) error
FormDataContentType() string
Close() error
}
type defaultForm struct {
writer *multipart.Writer
}
func newDefaultForm(body io.Writer) FormFactory {
return &defaultForm{
writer: multipart.NewWriter(body),
}
}
func (f *defaultForm) CreateFormFile(fieldname string, filepath string) error {
fWriter, err := f.writer.CreateFormFile(fieldname, filepath)
if err != nil {
return errors.Wrap(err, "CreateFormFile error")
}
file, err := os.Open(filepath)
if err != nil {
return errors.Wrapf(err, "read file: %s error", filepath)
}
defer file.Close()
_, err = io.Copy(fWriter, file)
if err != nil {
return errors.Wrap(err, "copy file from local error")
}
return nil
}
func (f *defaultForm) WriteField(fieldname string, value string) error {
err := f.writer.WriteField(fieldname, value)
if err != nil {
return errors.Wrap(err, "WriteField error")
}
return nil
}
func (f *defaultForm) FormDataContentType() string {
return f.writer.FormDataContentType()
}
func (f *defaultForm) Close() error {
return f.writer.Close()
}