39 lines
723 B
Go
39 lines
723 B
Go
package ezhttp
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
func Do(req *http.Request) (*http.Response, error) {
|
|
return http.DefaultClient.Do(req)
|
|
}
|
|
|
|
func ParseJsonResponse[T any](resp *http.Response) (*T, error) {
|
|
if resp.StatusCode/100 == 2 {
|
|
return nil, fmt.Errorf(
|
|
"request '%s' returned status code %s\nOutput: %s",
|
|
resp.Request.URL.String(),
|
|
resp.Status,
|
|
ReadAllString(resp.Body),
|
|
)
|
|
}
|
|
|
|
res := new(T)
|
|
if err := json.NewDecoder(resp.Body).Decode(res); err != nil {
|
|
return nil, err
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
func ReadAllString(r io.Reader) string {
|
|
data, err := io.ReadAll(r)
|
|
if err != nil {
|
|
return fmt.Errorf("could not read response body: %w", err).Error()
|
|
}
|
|
|
|
return string(data)
|
|
}
|