github.com/Finschia/finschia-sdk@v0.48.1/testutil/rest.go (about)

     1  package testutil
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  )
     7  
     8  // GetRequestWithHeaders defines a wrapper around an HTTP GET request with a provided URL
     9  // and custom headers
    10  // An error is returned if the request or reading the body fails.
    11  func GetRequestWithHeaders(url string, headers map[string]string) ([]byte, error) {
    12  	req, err := http.NewRequest("GET", url, nil)
    13  	if err != nil {
    14  		return nil, err
    15  	}
    16  
    17  	client := &http.Client{}
    18  
    19  	for key, value := range headers {
    20  		req.Header.Set(key, value)
    21  	}
    22  
    23  	res, err := client.Do(req)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	body, err := io.ReadAll(res.Body)
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  
    33  	if err = res.Body.Close(); err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	return body, nil
    38  }