generated from ZEISS/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
body.go
75 lines (60 loc) · 1.62 KB
/
body.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
package carry
import (
"bytes"
"encoding/json"
"io"
"strings"
goquery "github.com/google/go-querystring/query"
)
// BodyProvider provides Body content for http.Request attachment.
type BodyProvider interface {
// ContentType returns the Content-Type of the body.
ContentType() string
// Body returns the io.Reader body.
Body() (io.Reader, error)
}
// bodyProvider provides the wrapped body value as a Body for reqests.
type bodyProvider struct {
body io.Reader
}
// ContentType returns the Content-Type of the body.
func (p bodyProvider) ContentType() string {
return ""
}
// Body returns the io.Reader body.
func (p bodyProvider) Body() (io.Reader, error) {
return p.body, nil
}
type jsonBodyProvider struct {
payload interface{}
}
// ContentType returns the Content-Type of the body.
func (p jsonBodyProvider) ContentType() string {
return jsonContentType
}
// Body returns the io.Reader body.
func (p jsonBodyProvider) Body() (io.Reader, error) {
buf := &bytes.Buffer{}
err := json.NewEncoder(buf).Encode(p.payload)
if err != nil {
return nil, err
}
return buf, nil
}
// formBodyProvider encodes a url tagged struct value as Body for requests.
// See https://godoc.org/github.com/google/go-querystring/query for details.
type formBodyProvider struct {
payload interface{}
}
// ContentType returns the Content-Type of the body.
func (p formBodyProvider) ContentType() string {
return formContentType
}
// Body returns the io.Reader body.
func (p formBodyProvider) Body() (io.Reader, error) {
values, err := goquery.Values(p.payload)
if err != nil {
return nil, err
}
return strings.NewReader(values.Encode()), nil
}