-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathhttp_client.go
71 lines (58 loc) · 1.74 KB
/
http_client.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
70
71
package ethadapter
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/ethereum/go-ethereum"
)
// BaseHTTPClient provides common HTTP functionality for different clients
type BaseHTTPClient struct {
client *http.Client
baseURL string
}
func NewBaseHTTPClient(client *http.Client, baseURL string) *BaseHTTPClient {
return &BaseHTTPClient{client: client, baseURL: baseURL}
}
func (chc *BaseHTTPClient) Request(ctx context.Context, dest any, reqPath string, reqQuery url.Values) error {
base := chc.baseURL
if !strings.HasPrefix(base, "http://") && !strings.HasPrefix(base, "https://") {
base = "http://" + base
}
baseURL, err := url.Parse(base)
if err != nil {
return fmt.Errorf("failed to parse base URL: %w", err)
}
reqURL, err := baseURL.Parse(reqPath)
if err != nil {
return fmt.Errorf("failed to parse request path: %w", err)
}
reqURL.RawQuery = reqQuery.Encode()
headers := http.Header{}
headers.Add("Accept", "application/json")
req, err := http.NewRequestWithContext(ctx, "GET", reqURL.String(), nil)
if err != nil {
return fmt.Errorf("failed to create HTTP request: %w", err)
}
req.Header = headers
resp, err := chc.client.Do(req)
if err != nil {
return fmt.Errorf("http Get failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
errMsg, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed request with status %d: %s: %w", resp.StatusCode, string(errMsg), ethereum.NotFound)
} else if resp.StatusCode != http.StatusOK {
errMsg, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed request with status %d: %s", resp.StatusCode, string(errMsg))
}
err = json.NewDecoder(resp.Body).Decode(dest)
if err != nil {
return err
}
return nil
}