ソースを参照

extract resperr.go

marco 1 年間 前
コミット
224bd5b383
2 ファイル変更46 行追加36 行削除
  1. 0 36
      pkg/apiclient/client.go
  2. 46 0
      pkg/apiclient/resperr.go

+ 0 - 36
pkg/apiclient/client.go

@@ -4,9 +4,7 @@ import (
 	"context"
 	"context"
 	"crypto/tls"
 	"crypto/tls"
 	"crypto/x509"
 	"crypto/x509"
-	"encoding/json"
 	"fmt"
 	"fmt"
-	"io"
 	"net/http"
 	"net/http"
 	"net/url"
 	"net/url"
 
 
@@ -167,44 +165,10 @@ type Response struct {
 	//...
 	//...
 }
 }
 
 
-type ErrorResponse struct {
-	models.ErrorResponse
-}
-
-func (e *ErrorResponse) Error() string {
-	err := fmt.Sprintf("API error: %s", *e.Message)
-	if len(e.Errors) > 0 {
-		err += fmt.Sprintf(" (%s)", e.Errors)
-	}
-
-	return err
-}
-
 func newResponse(r *http.Response) *Response {
 func newResponse(r *http.Response) *Response {
 	return &Response{Response: r}
 	return &Response{Response: r}
 }
 }
 
 
-func CheckResponse(r *http.Response) error {
-	if c := r.StatusCode; 200 <= c && c <= 299 || c == 304 {
-		return nil
-	}
-
-	errorResponse := &ErrorResponse{}
-
-	data, err := io.ReadAll(r.Body)
-	if err == nil && len(data)>0 {
-		err := json.Unmarshal(data, errorResponse)
-		if err != nil {
-			return fmt.Errorf("http code %d, invalid body: %w", r.StatusCode, err)
-		}
-	} else {
-		errorResponse.Message = new(string)
-		*errorResponse.Message = fmt.Sprintf("http code %d, no error message", r.StatusCode)
-	}
-
-	return errorResponse
-}
-
 type ListOpts struct {
 type ListOpts struct {
 	//Page    int
 	//Page    int
 	//PerPage int
 	//PerPage int

+ 46 - 0
pkg/apiclient/resperr.go

@@ -0,0 +1,46 @@
+package apiclient
+
+import (
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+
+	"github.com/crowdsecurity/go-cs-lib/ptr"
+
+	"github.com/crowdsecurity/crowdsec/pkg/models"
+)
+
+type ErrorResponse struct {
+	models.ErrorResponse
+}
+
+func (e *ErrorResponse) Error() string {
+	err := fmt.Sprintf("API error: %s", *e.Message)
+	if len(e.Errors) > 0 {
+		err += fmt.Sprintf(" (%s)", e.Errors)
+	}
+
+	return err
+}
+
+// CheckResponse verifies the API response and builds an appropriate Go error if necessary.
+func CheckResponse(r *http.Response) error {
+	if c := r.StatusCode; 200 <= c && c <= 299 || c == 304 {
+		return nil
+	}
+
+	ret := &ErrorResponse{}
+
+	data, err := io.ReadAll(r.Body)
+	if err != nil || len(data) == 0 {
+		ret.Message = ptr.Of(fmt.Sprintf("http code %d, no error message", r.StatusCode))
+		return ret
+	}
+
+	if err := json.Unmarshal(data, ret); err != nil {
+		return fmt.Errorf("http code %d, invalid body: %w", r.StatusCode, err)
+	}
+
+	return ret
+}