From eef9c1870b36bcdbffa6a6c37d95446c833e7e76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Thu, 8 Jul 2021 20:50:59 +0200 Subject: [PATCH] client: Implement HTTP client with basic auth and GET request --- mailman/mailman_client.go | 71 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 mailman/mailman_client.go diff --git a/mailman/mailman_client.go b/mailman/mailman_client.go new file mode 100644 index 0000000..3014ab1 --- /dev/null +++ b/mailman/mailman_client.go @@ -0,0 +1,71 @@ +package mailman + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "time" +) + +type Client struct { + baseURL string + httpClient *http.Client + credentials *ClientCredentials +} + +type ClientCredentials struct { + Username string + Password string +} + +func NewMailmanCLient(url string, username string, password string) (*Client, error) { + httpClient := &http.Client{ + Timeout: time.Second * 3, + } + + clientCredentials := &ClientCredentials{ + Username: username, + Password: password, + } + + client := Client{ + baseURL: url, + httpClient: httpClient, + credentials: clientCredentials, + } + + return &client, nil +} + +func (client *Client) get(path string, resource interface{}) error { + resourceURL := client.baseURL + path + + req, err := http.NewRequest(http.MethodGet, resourceURL, nil) + if err != nil { + return nil + } + + req.SetBasicAuth(client.credentials.Username, client.credentials.Password) + resp, err := client.httpClient.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + if resp.StatusCode > 400 { + return fmt.Errorf("API error code: %d", resp.StatusCode) + } + + responseBody, err := ioutil.ReadAll(resp.Body) + if err != nil { + return err + } + + err = json.Unmarshal(responseBody, &resource) + if err != nil { + return err + } + + return nil +} -- 2.44.0