github.com/crowdsecurity/crowdsec@v1.6.1/pkg/apiclient/resperr.go (about) 1 package apiclient 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "net/http" 8 9 "github.com/crowdsecurity/go-cs-lib/ptr" 10 11 "github.com/crowdsecurity/crowdsec/pkg/models" 12 ) 13 14 type ErrorResponse struct { 15 models.ErrorResponse 16 } 17 18 func (e *ErrorResponse) Error() string { 19 err := fmt.Sprintf("API error: %s", *e.Message) 20 if len(e.Errors) > 0 { 21 err += fmt.Sprintf(" (%s)", e.Errors) 22 } 23 24 return err 25 } 26 27 // CheckResponse verifies the API response and builds an appropriate Go error if necessary. 28 func CheckResponse(r *http.Response) error { 29 if c := r.StatusCode; 200 <= c && c <= 299 || c == 304 { 30 return nil 31 } 32 33 ret := &ErrorResponse{} 34 35 data, err := io.ReadAll(r.Body) 36 if err != nil || len(data) == 0 { 37 ret.Message = ptr.Of(fmt.Sprintf("http code %d, no error message", r.StatusCode)) 38 return ret 39 } 40 41 if err := json.Unmarshal(data, ret); err != nil { 42 return fmt.Errorf("http code %d, invalid body: %w", r.StatusCode, err) 43 } 44 45 return ret 46 }