github.com/Finschia/finschia-sdk@v0.48.1/testutil/rest/rest.go (about) 1 // Package rest provides HTTP types and primitives for REST 2 // requests validation and responses handling. 3 package rest 4 5 import ( 6 "bytes" 7 "fmt" 8 "io" 9 "net/http" 10 ) 11 12 // GetRequest defines a wrapper around an HTTP GET request with a provided URL. 13 // An error is returned if the request or reading the body fails. 14 func GetRequest(url string) ([]byte, error) { 15 res, err := http.Get(url) // nolint:gosec 16 if err != nil { 17 return nil, err 18 } 19 defer res.Body.Close() 20 21 body, err := io.ReadAll(res.Body) 22 if err != nil { 23 return nil, err 24 } 25 26 return body, nil 27 } 28 29 // PostRequest defines a wrapper around an HTTP POST request with a provided URL and data. 30 // An error is returned if the request or reading the body fails. 31 func PostRequest(url string, contentType string, data []byte) ([]byte, error) { 32 res, err := http.Post(url, contentType, bytes.NewBuffer(data)) // nolint:gosec 33 if err != nil { 34 return nil, fmt.Errorf("error while sending post request: %w", err) 35 } 36 defer res.Body.Close() 37 38 bz, err := io.ReadAll(res.Body) 39 if err != nil { 40 return nil, fmt.Errorf("error reading response body: %w", err) 41 } 42 43 return bz, nil 44 }