github.com/cosmos/cosmos-sdk@v0.50.10/testutil/rest.go (about)

     1  package testutil
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  )
     9  
    10  // GetRequestWithHeaders defines a wrapper around an HTTP GET request with a provided URL
    11  // and custom headers
    12  // An error is returned if the request or reading the body fails.
    13  func GetRequestWithHeaders(url string, headers map[string]string) ([]byte, error) {
    14  	req, err := http.NewRequest("GET", url, nil)
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  
    19  	client := &http.Client{}
    20  
    21  	for key, value := range headers {
    22  		req.Header.Set(key, value)
    23  	}
    24  
    25  	res, err := client.Do(req)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  
    30  	body, err := io.ReadAll(res.Body)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  
    35  	if err = res.Body.Close(); err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	return body, nil
    40  }
    41  
    42  // GetRequest defines a wrapper around an HTTP GET request with a provided URL.
    43  // An error is returned if the request or reading the body fails.
    44  func GetRequest(url string) ([]byte, error) {
    45  	res, err := http.Get(url) //nolint:gosec // only used for testing
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	defer func() {
    50  		_ = res.Body.Close()
    51  	}()
    52  
    53  	body, err := io.ReadAll(res.Body)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  
    58  	return body, nil
    59  }
    60  
    61  // PostRequest defines a wrapper around an HTTP POST request with a provided URL and data.
    62  // An error is returned if the request or reading the body fails.
    63  func PostRequest(url, contentType string, data []byte) ([]byte, error) {
    64  	res, err := http.Post(url, contentType, bytes.NewBuffer(data)) //nolint:gosec // only used	for testing
    65  	if err != nil {
    66  		return nil, fmt.Errorf("error while sending post request: %w", err)
    67  	}
    68  	defer func() {
    69  		_ = res.Body.Close()
    70  	}()
    71  
    72  	bz, err := io.ReadAll(res.Body)
    73  	if err != nil {
    74  		return nil, fmt.Errorf("error reading response body: %w", err)
    75  	}
    76  
    77  	return bz, nil
    78  }