-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_data.go
More file actions
56 lines (50 loc) · 1.37 KB
/
Copy pathrequest_data.go
File metadata and controls
56 lines (50 loc) · 1.37 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
package hypert
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
)
// RequestData is some data related to the request, that can be used to create filename in the NamingScheme's FileNames method implementations or during request validation.
// The fields are cloned from request's fields and their modification will not affect actual request's values.
type RequestData struct {
Headers http.Header
URL *url.URL
Method string
BodyBytes []byte
}
func (r RequestData) String() string {
return fmt.Sprintf("%s %s", r.Method, r.URL)
}
func cloneURL(u *url.URL) *url.URL {
if u == nil { // this shouldn't actually happen, unless there is very weird injected clients' transport setup
return nil
}
var userInfo *url.Userinfo
if u.User != nil {
userInfoCopy := *u.User
userInfo = &userInfoCopy
}
uCopy := *u
uCopy.User = userInfo
return &uCopy
}
func requestDataFromRequest(req *http.Request) (RequestData, error) {
if req.Body == nil {
req.Body = http.NoBody
}
var originalReqBody bytes.Buffer
teeReader := io.TeeReader(req.Body, &originalReqBody)
req.Body = io.NopCloser(&originalReqBody)
gotBodyBytes, err := io.ReadAll(teeReader)
if err != nil {
return RequestData{}, fmt.Errorf("read request body: %w", err)
}
return RequestData{
Headers: req.Header.Clone(),
URL: cloneURL(req.URL),
Method: req.Method,
BodyBytes: gotBodyBytes,
}, nil
}