-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest_body.go
44 lines (38 loc) · 1.25 KB
/
request_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
package gostman
import (
"bytes"
"encoding/json"
"io"
"net/url"
"strconv"
"strings"
"github.com/sirupsen/logrus"
)
// Body sets request body.
func (r *Request) Body(body io.Reader, contentType string, contentLength int) {
r.body = body
r.headers.Set("Content-Type", contentType)
r.headers.Set("Content-Length", strconv.Itoa(contentLength))
}
// BodyJSON creates request body by marshaling v using JSON.
// Returns io.Reader, Content-Type of application/json, and its length.
func BodyJSON(v interface{}) (io.Reader, string, int) {
var buff bytes.Buffer
if err := json.NewEncoder(&buff).Encode(v); err != nil {
logrus.Fatal(err)
}
return &buff, "application/json", buff.Len()
}
// BodyFormURLEncoded creates request body by encoding url values.
// Returns io.Reader, Content-Type of application/x-www-form-urlencoded, and its length.
func BodyFormURLEncoded(f func(url.Values)) (io.Reader, string, int) {
v := make(url.Values)
f(v)
form := v.Encode()
return strings.NewReader(form), "application/x-www-form-urlencoded", len(form)
}
// Body Text creates request body using raw text.
// Returns io.Reader, Content-Type of text/plain, and its length.
func BodyText(s string) (io.Reader, string, int) {
return strings.NewReader(s), "text/plain", len(s)
}