-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttpservice.go
More file actions
299 lines (256 loc) · 8.65 KB
/
httpservice.go
File metadata and controls
299 lines (256 loc) · 8.65 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/textproto"
"strings"
"time"
)
// HTTPService handles HTTP requests for the Postman-like client
type HTTPService struct {
client *http.Client
logService *LogService
collectionService *CollectionService
}
// NewHTTPService creates a new HTTP service
func NewHTTPService() *HTTPService {
return &HTTPService{
client: &http.Client{
Timeout: 30 * time.Second,
},
logService: NewLogService(),
collectionService: NewCollectionService(),
}
}
// NewHTTPServiceWithCollection creates a new HTTP service with a shared collection service
func NewHTTPServiceWithCollection(collectionService *CollectionService) *HTTPService {
return &HTTPService{
client: &http.Client{
Timeout: 30 * time.Second,
},
logService: NewLogService(),
collectionService: collectionService,
}
}
// HTTPRequest represents an HTTP request structure
type HTTPRequest struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
CollectionID string `json:"collectionId,omitempty"`
}
// HTTPResponse represents an HTTP response structure
type HTTPResponse struct {
StatusCode int `json:"statusCode"`
Status string `json:"status"`
Headers map[string]string `json:"headers"`
RequestHeaders map[string]string `json:"requestHeaders"`
Body string `json:"body"`
Duration int64 `json:"duration"` // in milliseconds
Size int64 `json:"size"` // response size in bytes
}
// SendRequest sends an HTTP request and returns the response
func (h *HTTPService) SendRequest(ctx context.Context, req HTTPRequest) (*HTTPResponse, error) {
start := time.Now()
// Resolve URL with collection environment base URL if needed
resolvedURL, err := h.resolveURL(ctx, req.URL, req.CollectionID)
if err != nil {
return nil, fmt.Errorf("failed to resolve URL: %w", err)
}
req.URL = resolvedURL
// Merge collection environment headers with request headers
if req.CollectionID != "" && h.collectionService != nil {
req.Headers, err = h.mergeCollectionHeaders(ctx, req.CollectionID, req.Headers)
if err != nil {
// Log warning but don't fail the request
fmt.Printf("Warning: failed to merge collection headers: %v\n", err)
}
}
// Validate and clean JSON body if content-type is JSON
if req.Body != "" {
contentType := req.Headers["Content-Type"]
if contentType == "" {
contentType = req.Headers["content-type"]
}
if strings.Contains(strings.ToLower(contentType), "application/json") {
// Validate JSON format
var jsonTest interface{}
if err := json.Unmarshal([]byte(req.Body), &jsonTest); err != nil {
return nil, fmt.Errorf("invalid JSON body: %w", err)
}
// Re-marshal to ensure clean JSON
cleanJSON, err := json.Marshal(jsonTest)
if err != nil {
return nil, fmt.Errorf("failed to clean JSON: %w", err)
}
req.Body = string(cleanJSON)
}
}
// Create HTTP request
var bodyReader io.Reader
if req.Body != "" {
bodyReader = strings.NewReader(req.Body)
}
httpReq, err := http.NewRequestWithContext(ctx, req.Method, req.URL, bodyReader)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
// Set headers
for key, value := range req.Headers {
httpReq.Header.Set(key, value)
}
// Send request
resp, err := h.client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
// Read response body
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
// Calculate duration
duration := time.Since(start).Milliseconds()
// Convert headers to map
headers := make(map[string]string)
for key, values := range resp.Header {
headers[key] = strings.Join(values, ", ")
}
// Capture the final request headers, including those added by the client
// by dumping the request and parsing the headers back.
// We dump without the body to avoid consuming the body reader.
dump, err := httputil.DumpRequestOut(httpReq, false)
if err != nil {
return nil, fmt.Errorf("failed to dump request for header capture: %w", err)
}
reader := bufio.NewReader(bytes.NewReader(dump))
parsedReq, err := http.ReadRequest(reader)
if err != nil {
return nil, fmt.Errorf("failed to parse dumped request: %w", err)
}
reqHeaders := make(map[string]string)
for key, values := range parsedReq.Header {
reqHeaders[key] = strings.Join(values, ", ")
}
// Create response object
response := &HTTPResponse{
StatusCode: resp.StatusCode,
Status: resp.Status,
Headers: headers,
RequestHeaders: reqHeaders,
Body: string(bodyBytes),
Duration: duration,
Size: int64(len(bodyBytes)),
}
// Log the request and response
if h.logService != nil {
_ = h.logService.LogRequest(ctx, req, response, duration)
}
return response, nil
}
// ValidateURL checks if a URL is valid
func (h *HTTPService) ValidateURL(url string) bool {
if url == "" {
return false
}
// Add http:// if no protocol specified
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
url = "http://" + url
}
req, err := http.NewRequest("GET", url, nil)
return err == nil && req.URL != nil
}
// GetSupportedMethods returns a list of supported HTTP methods
func (h *HTTPService) GetSupportedMethods(ctx context.Context) []string {
return []string{"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"}
}
// resolveURL resolves a URL using the active environment's base URL from the collection if needed
func (h *HTTPService) resolveURL(ctx context.Context, url string, collectionID string) (string, error) {
// If URL is already absolute, return it as is
if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
return url, nil
}
// If no collection ID is provided, return the URL as-is (relative)
if collectionID == "" {
return url, nil
}
// Get active environment for the collection
activeEnv, err := h.collectionService.GetActiveCollectionEnvironment(ctx, collectionID)
if err != nil {
return "", fmt.Errorf("failed to get active environment for collection %s: %w", collectionID, err)
}
// Ensure base URL doesn't end with a slash
baseURL := strings.TrimSuffix(activeEnv.BaseURL, "/")
// Ensure URL doesn't start with a slash
relativeURL := strings.TrimPrefix(url, "/")
// Combine base URL and relative URL
return baseURL + "/" + relativeURL, nil
}
// GetRequestLogs returns all logged requests
func (h *HTTPService) GetRequestLogs(ctx context.Context) ([]RequestLog, error) {
if h.logService == nil {
return []RequestLog{}, nil
}
return h.logService.GetAllLogs(ctx)
}
// GetRequestLogByID returns a specific log by ID
func (h *HTTPService) GetRequestLogByID(ctx context.Context, id string) (*RequestLog, error) {
if h.logService == nil {
return nil, nil
}
return h.logService.GetLogByID(ctx, id)
}
// ClearRequestLogs removes all logged requests
func (h *HTTPService) ClearRequestLogs(ctx context.Context) error {
if h.logService == nil {
return nil
}
return h.logService.ClearLogs(ctx)
}
// GetRequestLogsCount returns the number of logged requests
func (h *HTTPService) GetRequestLogsCount(ctx context.Context) (int, error) {
if h.logService == nil {
return 0, nil
}
return h.logService.GetLogsCount(ctx)
}
// ExportRequestLogsAsJSON exports all logs as JSON string
func (h *HTTPService) ExportRequestLogsAsJSON(ctx context.Context) (string, error) {
if h.logService == nil {
return "[]", nil
}
return h.logService.ExportLogsAsJSON(ctx)
}
// mergeCollectionHeaders returns request headers as-is since environment headers are now managed separately
func (h *HTTPService) mergeCollectionHeaders(ctx context.Context, collectionID string, requestHeaders map[string]string) (map[string]string, error) {
// Start with a new map to avoid mutating the original
merged := make(map[string]string)
// Bring in active header collection (if any)
if h.collectionService != nil {
hc, err := h.collectionService.GetActiveHeaderCollection(ctx, collectionID)
if err != nil {
// Surface error to caller to optionally warn but not fail request
return nil, err
}
if hc != nil && hc.Headers != nil {
for k, v := range hc.Headers {
ck := textproto.CanonicalMIMEHeaderKey(k)
merged[ck] = v
}
}
}
// Overlay request-specific headers (take precedence)
for k, v := range requestHeaders {
ck := textproto.CanonicalMIMEHeaderKey(k)
merged[ck] = v
}
return merged, nil
}