forked from pbnjay/harhar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_request.go
69 lines (63 loc) · 1.88 KB
/
convert_request.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
67
68
69
package harhar
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
func ConvertRequestIntoHttpRequest(req Request) (*http.Request, error) {
r := bytes.NewReader([]byte(req.Body.Content))
query := ""
if len(req.QueryParams) > 0 {
query = "?"
for x, param := range req.QueryParams {
amp := "&"
if x < len(req.QueryParams)-1 {
amp = ""
}
query += fmt.Sprintf("%s=%s%s", param.Name, param.Value, amp)
}
}
httpRequest, err := http.NewRequest(req.Method, fmt.Sprintf("%s%s", req.URL, query), nil)
values := make(url.Values)
for _, param := range req.Body.Params {
decoded, _ := url.QueryUnescape(param.Value)
values.Add(param.Name, decoded)
}
if req.Method == http.MethodPost || req.Method == http.MethodPut || req.Method == http.MethodPatch {
httpRequest.PostForm = values
httpRequest.Form = values
}
if err != nil {
return nil, err
}
for _, header := range req.Headers {
if !strings.HasPrefix(header.Name, ":") {
httpRequest.Header.Set(header.Name, header.Value)
}
}
for _, cookie := range req.Cookies {
httpRequest.AddCookie(&http.Cookie{
Name: cookie.Name,
Value: cookie.Value,
Path: cookie.Path,
Domain: cookie.Domain,
Expires: time.Now().Add(24 * time.Hour),
HttpOnly: cookie.HTTPOnly,
Secure: cookie.Secure,
})
}
if req.Body.MIMEType != "" {
httpRequest.Header.Set("Content-Type", req.Body.MIMEType)
}
body, err := io.ReadAll(r)
if err != nil {
return nil, err
}
httpRequest.Body = io.NopCloser(bytes.NewReader(body))
httpRequest.ContentLength = int64(len(body))
return httpRequest, nil
}