3 Commits

Author SHA1 Message Date
1c3a45729b fixed status check 2025-02-02 20:06:45 +01:00
f5ff99a2a8 ParseJsonResponse returns error based on status code 2025-02-02 20:02:13 +01:00
d144bb5a47 Update go.mod 2024-12-16 19:43:10 +01:00
2 changed files with 22 additions and 3 deletions

23
do.go
View File

@ -2,6 +2,7 @@ package ezhttp
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"net/http" "net/http"
) )
@ -10,10 +11,28 @@ func Do(req *http.Request) (*http.Response, error) {
return http.DefaultClient.Do(req) 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) 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 nil, err
} }
return res, nil 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)
}

2
go.mod
View File

@ -1,3 +1,3 @@
module git.milar.in/milarin/ezhttp module git.tordarus.net/tordarus/ezhttp
go 1.23.0 go 1.23.0