github.com/SAP/jenkins-library@v1.362.0/pkg/contrast/request.go (about)

     1  package contrast
     2  
     3  import (
     4  	"encoding/json"
     5  	"io"
     6  	"net/http"
     7  	"time"
     8  
     9  	"github.com/SAP/jenkins-library/pkg/log"
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  type ContrastHttpClient interface {
    14  	ExecuteRequest(url string, params map[string]string, dest interface{}) error
    15  }
    16  
    17  type ContrastHttpClientInstance struct {
    18  	apiKey string
    19  	auth   string
    20  }
    21  
    22  func NewContrastHttpClient(apiKey, auth string) *ContrastHttpClientInstance {
    23  	return &ContrastHttpClientInstance{
    24  		apiKey: apiKey,
    25  		auth:   auth,
    26  	}
    27  }
    28  
    29  func (c *ContrastHttpClientInstance) ExecuteRequest(url string, params map[string]string, dest interface{}) error {
    30  	req, err := newHttpRequest(url, c.apiKey, c.auth, params)
    31  	if err != nil {
    32  		return errors.Wrap(err, "failed to create request")
    33  	}
    34  
    35  	log.Entry().Debugf("GET call request to: %s", url)
    36  	response, err := performRequest(req)
    37  	if response != nil && response.StatusCode != http.StatusOK {
    38  		return errors.Errorf("failed to perform request, status code: %v and status %v", response.StatusCode, response.Status)
    39  	}
    40  
    41  	if err != nil {
    42  		return errors.Wrap(err, "failed to perform request")
    43  	}
    44  	defer response.Body.Close()
    45  	err = parseJsonResponse(response, dest)
    46  	if err != nil {
    47  		return errors.Wrap(err, "failed to parse JSON response")
    48  	}
    49  	return nil
    50  }
    51  
    52  func newHttpRequest(url, apiKey, auth string, params map[string]string) (*http.Request, error) {
    53  	req, err := http.NewRequest("GET", url, nil)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  	req.Header.Add("API-Key", apiKey)
    58  	req.Header.Add("Authorization", auth)
    59  	q := req.URL.Query()
    60  	for param, value := range params {
    61  		q.Add(param, value)
    62  	}
    63  	req.URL.RawQuery = q.Encode()
    64  	return req, nil
    65  }
    66  func performRequest(req *http.Request) (*http.Response, error) {
    67  	client := http.Client{
    68  		Timeout: 30 * time.Second,
    69  	}
    70  	response, err := client.Do(req)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  	return response, nil
    75  }
    76  
    77  func parseJsonResponse(response *http.Response, jsonData interface{}) error {
    78  	data, err := io.ReadAll(response.Body)
    79  	if err != nil {
    80  		return err
    81  	}
    82  	err = json.Unmarshal(data, jsonData)
    83  	if err != nil {
    84  		return err
    85  	}
    86  	return nil
    87  }