-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathteebody.go
66 lines (51 loc) · 1.17 KB
/
teebody.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
package proxy
import (
"io"
"net/http"
"net/url"
log "github.com/sirupsen/logrus"
)
type teeTie struct {
r io.Reader
w *io.PipeWriter
}
func (tt *teeTie) Read(b []byte) (int, error) {
n, err := tt.r.Read(b)
if err != nil && err != io.EOF {
tt.w.CloseWithError(err)
return n, err
}
if n > 0 {
if _, werr := tt.w.Write(b[:n]); werr != nil {
log.Error("tee: error while tee request", werr)
}
}
if err == io.EOF {
tt.w.Close()
}
return n, err
}
func (tt *teeTie) Close() error { return nil }
// Returns the cloned request and the tee body to be used on the main request.
func cloneRequestForSplit(u *url.URL, req *http.Request) (*http.Request, io.ReadCloser, error) {
h := make(http.Header)
for k, v := range req.Header {
h[k] = v
}
var teeBody io.ReadCloser
mainBody := req.Body
if req.ContentLength != 0 {
pr, pw := io.Pipe()
teeBody = pr
mainBody = &teeTie{mainBody, pw}
}
clone, err := http.NewRequest(req.Method, u.String(), teeBody)
if err != nil {
return nil, nil, err
}
clone.RequestURI = req.RequestURI
clone.Header = h
clone.ContentLength = req.ContentLength
clone.RemoteAddr = req.RemoteAddr
return clone, mainBody, nil
}