-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapiservice.go
More file actions
154 lines (131 loc) · 3.81 KB
/
apiservice.go
File metadata and controls
154 lines (131 loc) · 3.81 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
package main
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"strings"
"time"
"net"
)
type APIResponse struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
Body interface{} `json:"body"`
TimeMs int64 `json:"timeMs"`
Error string `json:"error,omitempty"`
UsedURL string `json:"usedURL,omitempty"`
}
type RequestConfig struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers"`
QueryParams map[string]string `json:"queryParams"`
Body string `json:"body"`
}
type APIService struct{}
func NewAPIService() *APIService {
return &APIService{}
}
func (a *APIService) SendRequest(config RequestConfig) (*APIResponse, error) {
startTime := time.Now()
reqURL := config.URL
hasScheme := strings.HasPrefix(reqURL, "http://") || strings.HasPrefix(reqURL, "https://")
if !hasScheme {
reqURL = "http://" + reqURL
}
finalURL := reqURL
sendRequest := func(url string) (*http.Response, error) {
currentURL := url
if len(config.QueryParams) > 0 {
req, err := http.NewRequest(config.Method, url, nil)
if err != nil {
return nil, err
}
q := req.URL.Query()
for key, value := range config.QueryParams {
q.Add(key, value)
}
req.URL.RawQuery = q.Encode()
currentURL = req.URL.String()
}
var reqBody io.Reader
if config.Body != "" {
reqBody = bytes.NewBufferString(config.Body)
}
req, err := http.NewRequest(config.Method, currentURL, reqBody)
if err != nil {
return nil, err
}
for key, value := range config.Headers {
req.Header.Add(key, value)
}
if config.Method != "GET" && config.Method != "HEAD" && req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}
client := &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
log.Printf("Redirecting to: %s", req.URL.String())
return nil
},
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
finalURL = resp.Request.URL.String()
return resp, nil
}
resp, err := sendRequest(reqURL)
if err != nil {
var shouldRetryWithHTTPS bool
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
shouldRetryWithHTTPS = true
} else if _, ok := err.(*net.OpError); ok {
shouldRetryWithHTTPS = true
} else if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial tcp") {
shouldRetryWithHTTPS = true
}
if shouldRetryWithHTTPS && strings.HasPrefix(reqURL, "http://") && !strings.HasPrefix(reqURL, "https://") {
log.Printf("HTTP request failed for %s: %v. Retrying with HTTPS...", reqURL, err)
httpsURL := "https://" + strings.TrimPrefix(reqURL, "http://")
resp, err = sendRequest(httpsURL)
if err != nil {
return &APIResponse{Error: err.Error()}, nil
}
} else {
return &APIResponse{Error: err.Error()}, nil
}
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
log.Printf("Error closing response body: %v", closeErr)
}
}()
headers := make(map[string]string)
for key, values := range resp.Header {
if len(values) > 0 {
headers[key] = values[0]
}
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return &APIResponse{Error: err.Error()}, nil
}
var bodyInterface interface{}
if err := json.Unmarshal(respBody, &bodyInterface); err != nil {
bodyInterface = string(respBody)
}
elapsedTime := time.Since(startTime).Milliseconds()
log.Printf("Sending APIResponse with UsedURL: %s", finalURL)
return &APIResponse{
StatusCode: resp.StatusCode,
Headers: headers,
Body: bodyInterface,
TimeMs: elapsedTime,
Error: "",
UsedURL: finalURL,
}, nil
}