-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
90 lines (75 loc) · 1.74 KB
/
request.go
File metadata and controls
90 lines (75 loc) · 1.74 KB
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
package httpc
import (
"context"
"fmt"
"io"
"net/http"
"sync"
)
// Request same as http.Request, but the Body is treated as io.Reader instead of io.ReadCloser.
// Even if the Body implements the io.Closer interface, the body will not be closed.
type Request struct {
*http.Request
Body io.Reader
}
func NewRequest(ctx context.Context, method, url string, body io.Reader) (*Request, error) {
req, err := http.NewRequestWithContext(ctx, method, url, nil)
if err != nil {
return nil, err
}
return &Request{Request: req, Body: body}, nil
}
func (r *Request) Clone(ctx context.Context) *Request {
rr := r.Request.Clone(ctx)
r2 := *r
r2.Request = rr
return &r2
}
type safeBody struct {
mux sync.Mutex
r io.Reader
}
func (b *safeBody) Close() error {
b.mux.Lock()
defer b.mux.Unlock()
b.r = nil
return nil
}
func (b *safeBody) Read(p []byte) (int, error) {
b.mux.Lock()
defer b.mux.Unlock()
if b.r == nil {
return 0, io.EOF
}
return b.r.Read(p)
}
func (r *Request) Build() *http.Request {
rr := r.Request.Clone(r.Context())
if r.Body == nil || r.Body == http.NoBody {
rr.Body = nil
rr.ContentLength = 0
} else {
rr.Body = &safeBody{r: r.Body}
}
return rr
}
// RequestSendError wraps the error returned by the Do() method.
type RequestSendError struct {
Err error
}
func (e *RequestSendError) Error() string {
return fmt.Sprintf("request send failed, %v", e.Err)
}
func (e *RequestSendError) Unwrap() error {
return e.Err
}
// SerializationError wraps any errors that occur while serializing the request.
type SerializationError struct {
Err error
}
func (e *SerializationError) Error() string {
return fmt.Sprintf("request serialization failed, %v", e.Err)
}
func (e *SerializationError) Unwrap() error {
return e.Err
}