Skip to content

Commit aadb254

Browse files
committed
feat: add request body support
Handle POST/PUT bodies with auto content-type
1 parent 4e85afb commit aadb254

2 files changed

Lines changed: 52 additions & 1 deletion

File tree

internal/http/manager.go

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package http
22

33
import (
4+
"encoding/json"
45
"fmt"
6+
"io"
57
"net/http"
68
"net/url"
79
"strings"
@@ -67,12 +69,22 @@ func (h *HTTPManager) ExecuteRequest(req *Request) (*Response, error) {
6769
}
6870

6971
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)
7179
if err != nil {
7280
log.Error("failed to create HTTP request", "error", err)
7381
return nil, fmt.Errorf("failed to create request: %w", err)
7482
}
7583

84+
if body != nil {
85+
h.setContentType(httpReq, req.Body)
86+
}
87+
7688
if err := h.setHeaders(httpReq, req.Headers); err != nil {
7789
log.Error("failed to set headers", "error", err)
7890
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
126138
}
127139
return nil
128140
}
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+
}

internal/http/manager_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,26 @@ func TestSetHeaders(t *testing.T) {
130130
t.Error("Content-Type header not set correctly")
131131
}
132132
}
133+
134+
func TestSetContentType(t *testing.T) {
135+
manager := NewHTTPManager()
136+
137+
tests := []struct {
138+
body string
139+
expected string
140+
}{
141+
{`{"key": "value"}`, "application/json"},
142+
{`[1, 2, 3]`, "application/json"},
143+
{"plain text", "text/plain"},
144+
}
145+
146+
for _, test := range tests {
147+
req, _ := http.NewRequest("POST", "https://example.com", nil)
148+
manager.setContentType(req, test.body)
149+
150+
if req.Header.Get("Content-Type") != test.expected {
151+
t.Errorf("for body %q, expected %q, got %q",
152+
test.body, test.expected, req.Header.Get("Content-Type"))
153+
}
154+
}
155+
}

0 commit comments

Comments
 (0)