ParseJsonResponse returns error based on status code
This commit is contained in:
parent
d144bb5a47
commit
f5ff99a2a8
23
do.go
23
do.go
@ -2,6 +2,7 @@ package ezhttp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
@ -10,10 +11,28 @@ func Do(req *http.Request) (*http.Response, error) {
|
||||
return http.DefaultClient.Do(req)
|
||||
}
|
||||
|
||||
func ParseJsonResponse[T any](r io.Reader) (*T, error) {
|
||||
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(r).Decode(res); err != nil {
|
||||
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)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user