-
Notifications
You must be signed in to change notification settings - Fork 11
/
encoder.go
110 lines (86 loc) · 2.27 KB
/
encoder.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
package tg
import (
"errors"
"fmt"
"io"
"mime/multipart"
"net/url"
"strings"
)
// Encoder represents request encoder.
type Encoder interface {
// Writes string argument k to encoder.
WriteString(k string, v string) error
// Write files argument k to encoder.
WriteFile(k string, file InputFile) error
}
type httpEncoder interface {
Encoder
io.Closer
ContentType() string
}
type urlEncodedEncoder struct {
dst io.Writer
pairs int
}
var _ httpEncoder = (*urlEncodedEncoder)(nil)
func newURLEncodedEncoder(dst io.Writer) *urlEncodedEncoder {
return &urlEncodedEncoder{dst: dst}
}
func (encoder *urlEncodedEncoder) WriteString(k string, v string) error {
buf := strings.Builder{}
if encoder.pairs > 0 {
buf.WriteByte('&')
}
buf.WriteString(url.QueryEscape(k))
buf.WriteByte('=')
buf.WriteString(url.QueryEscape(v))
_, err := io.WriteString(encoder.dst, buf.String())
if err != nil {
return err
}
encoder.pairs++
return nil
}
func (encoder *urlEncodedEncoder) WriteFile(k string, file InputFile) error {
return errors.New("urlEncodedEncoder doesn't support files")
}
func (encoder *urlEncodedEncoder) ContentType() string {
return "application/x-www-form-urlencoded"
}
func (encoder *urlEncodedEncoder) Close() error {
return nil
}
// multipartEncoder encodes the request using multipart encoding.
type multipartEncoder struct {
w *multipart.Writer
}
// newMultipartEncoder creates multipart encoder.
func newMultipartEncoder(writer io.Writer) *multipartEncoder {
return &multipartEncoder{
w: multipart.NewWriter(writer),
}
}
// AddString encodes string value
func (enc *multipartEncoder) WriteString(k string, v string) error {
return enc.w.WriteField(k, v)
}
// AddFile encodes file value.
func (enc *multipartEncoder) WriteFile(k string, file InputFile) error {
writer, err := enc.w.CreateFormFile(k, file.Name)
if err != nil {
return fmt.Errorf("create form file '%s': %w", k, err)
}
if _, err := io.Copy(writer, file.Body); err != nil {
return fmt.Errorf("copy to form file '%s': %w", k, err)
}
return nil
}
// ContentType returns HTTP request content type.
func (enc *multipartEncoder) ContentType() string {
return enc.w.FormDataContentType()
}
// Close multipart encoder.
func (enc *multipartEncoder) Close() error {
return enc.w.Close()
}