|
1 | 1 | package http |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "encoding/json" |
4 | 5 | "fmt" |
| 6 | + "io" |
5 | 7 | "net/http" |
6 | 8 | "net/url" |
7 | 9 | "strings" |
@@ -67,12 +69,22 @@ func (h *HTTPManager) ExecuteRequest(req *Request) (*Response, error) { |
67 | 69 | } |
68 | 70 |
|
69 | 71 | start := time.Now() |
70 | | - httpReq, err := http.NewRequest(strings.ToUpper(req.Method), requestURL, nil) |
| 72 | + |
| 73 | + var body io.Reader |
| 74 | + if req.Body != "" && (strings.ToUpper(req.Method) == "POST" || strings.ToUpper(req.Method) == "PUT" || strings.ToUpper(req.Method) == "PATCH") { |
| 75 | + body = strings.NewReader(req.Body) |
| 76 | + } |
| 77 | + |
| 78 | + httpReq, err := http.NewRequest(strings.ToUpper(req.Method), requestURL, body) |
71 | 79 | if err != nil { |
72 | 80 | log.Error("failed to create HTTP request", "error", err) |
73 | 81 | return nil, fmt.Errorf("failed to create request: %w", err) |
74 | 82 | } |
75 | 83 |
|
| 84 | + if body != nil { |
| 85 | + h.setContentType(httpReq, req.Body) |
| 86 | + } |
| 87 | + |
76 | 88 | if err := h.setHeaders(httpReq, req.Headers); err != nil { |
77 | 89 | log.Error("failed to set headers", "error", err) |
78 | 90 | return nil, fmt.Errorf("failed to set headers: %w", err) |
@@ -126,3 +138,19 @@ func (h *HTTPManager) setHeaders(req *http.Request, headers map[string]string) e |
126 | 138 | } |
127 | 139 | return nil |
128 | 140 | } |
| 141 | + |
| 142 | +func (h *HTTPManager) setContentType(req *http.Request, body string) { |
| 143 | + if req.Header.Get("Content-Type") != "" { |
| 144 | + return |
| 145 | + } |
| 146 | + |
| 147 | + body = strings.TrimSpace(body) |
| 148 | + if strings.HasPrefix(body, "{") || strings.HasPrefix(body, "[") { |
| 149 | + if json.Valid([]byte(body)) { |
| 150 | + req.Header.Set("Content-Type", "application/json") |
| 151 | + return |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + req.Header.Set("Content-Type", "text/plain") |
| 156 | +} |
0 commit comments