From 483f28f79b728d27b549d1a32fa716b289702601 Mon Sep 17 00:00:00 2001 From: Amisha Singla Date: Thu, 14 Nov 2024 17:18:24 -0600 Subject: [PATCH] Add basic util to request api --- utils/apiclient/client.go | 34 ++++++++++++++++++++++++++++++++++ utils/apiclient/client_test.go | 22 ++++++++++++++++++++++ utils/apiclient/main.go | 6 ++++++ 3 files changed, 62 insertions(+) create mode 100644 utils/apiclient/client.go create mode 100644 utils/apiclient/client_test.go create mode 100644 utils/apiclient/main.go diff --git a/utils/apiclient/client.go b/utils/apiclient/client.go new file mode 100644 index 0000000000..b7b28c9c0e --- /dev/null +++ b/utils/apiclient/client.go @@ -0,0 +1,34 @@ +package apiclient + +import ( + "fmt" + "net/http" + "net/url" + + "github.com/pkg/errors" +) + +func (c *APIClient) getRequest(endpoint string, queryParams url.Values) error { + fullURL := c.url(endpoint, queryParams) + req, err := http.NewRequest("GET", fullURL, nil) + if err != nil { + return errors.Wrap(err, "http GET request creation failed") + } + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return errors.Wrap(err, "http GET request failed") + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("API request failed with status %d", resp.StatusCode) + } + + return nil +} + +func (c *APIClient) url(endpoint string, qstr url.Values) string { + return fmt.Sprintf("%s/%s?%s", c.BaseURL, endpoint, qstr.Encode()) +} diff --git a/utils/apiclient/client_test.go b/utils/apiclient/client_test.go new file mode 100644 index 0000000000..8a808e37d1 --- /dev/null +++ b/utils/apiclient/client_test.go @@ -0,0 +1,22 @@ +package apiclient + +import ( + "net/url" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_url(t *testing.T) { + c := &APIClient{ + BaseURL: "https://stellar.org", + } + + qstr := url.Values{} + qstr.Add("type", "forward") + qstr.Add("federation_type", "bank_account") + qstr.Add("swift", "BOPBPHMM") + qstr.Add("acct", "2382376") + furl := c.url("federation", qstr) + assert.Equal(t, "https://stellar.org/federation?acct=2382376&federation_type=bank_account&swift=BOPBPHMM&type=forward", furl) +} diff --git a/utils/apiclient/main.go b/utils/apiclient/main.go new file mode 100644 index 0000000000..f2a5ef65dd --- /dev/null +++ b/utils/apiclient/main.go @@ -0,0 +1,6 @@ +package apiclient + +type APIClient struct { + BaseURL string + AuthToken string +}