ezhttp/do.go

39 lines
723 B
Go
Raw Permalink Normal View History

2024-09-11 13:32:52 +02:00
package ezhttp
import (
"encoding/json"
"fmt"
2024-09-11 13:32:52 +02:00
"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) {
2025-02-02 20:06:45 +01:00
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),
)
}
2024-09-11 13:32:52 +02:00
res := new(T)
if err := json.NewDecoder(resp.Body).Decode(res); err != nil {
2024-09-11 13:32:52 +02:00
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)
}