~xenrox/terraform-provider-mailman

eef9c1870b36bcdbffa6a6c37d95446c833e7e76 — Thorben Günther 2 years ago 902e248
client: Implement HTTP client with basic auth and GET request
1 files changed, 71 insertions(+), 0 deletions(-)

A mailman/mailman_client.go
A mailman/mailman_client.go => mailman/mailman_client.go +71 -0
@@ 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
}