/
body.go
59 lines (47 loc) · 1.09 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
package httpcli
import (
"bytes"
"io"
"net/http"
"net/url"
"github.com/integration-system/isp-kit/json"
)
type RequestBodyWriter interface {
Write(req *http.Request, w io.Writer) error
}
type jsonRequest struct {
value any
}
func (j jsonRequest) Write(req *http.Request, w io.Writer) error {
req.Header.Set("content-type", "application/json")
return json.EncodeInto(w, j.value)
}
type plainRequest struct {
value []byte
}
func (p plainRequest) Write(_ *http.Request, w io.Writer) error {
_, err := w.Write(p.value)
return err
}
type formRequest struct {
data map[string][]string
}
func (f formRequest) Write(req *http.Request, w io.Writer) error {
req.Header.Set("content-type", "application/x-www-form-urlencoded")
data := url.Values(f.data).Encode()
_, err := w.Write([]byte(data))
return err
}
type ResponseBodyReader interface {
Read(r io.Reader) error
}
type jsonResponse struct {
ptr any
}
func (j jsonResponse) Read(r io.Reader) error {
buff, isBuff := r.(*bytes.Buffer)
if isBuff {
return json.Unmarshal(buff.Bytes(), j.ptr)
}
return json.NewDecoder(r).Decode(j.ptr)
}