From 25df841e2b96cbcd6c65b69a012743f42146bb8f Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Wed, 13 May 2020 18:24:29 +0200 Subject: [PATCH] internal: move HTTPError to common file This is used by both clients and servers now. --- internal/internal.go | 34 ++++++++++++++++++++++++++++++++++ internal/server.go | 33 --------------------------------- 2 files changed, 34 insertions(+), 33 deletions(-) diff --git a/internal/internal.go b/internal/internal.go index 49e9997..08c2ef8 100644 --- a/internal/internal.go +++ b/internal/internal.go @@ -3,6 +3,7 @@ package internal import ( "fmt" + "net/http" ) // Depth indicates whether a request applies to the resource's members. It's @@ -65,3 +66,36 @@ func FormatOverwrite(overwrite bool) string { return "F" } } + +type HTTPError struct { + Code int + Err error +} + +func HTTPErrorFromError(err error) *HTTPError { + if err == nil { + return nil + } + if httpErr, ok := err.(*HTTPError); ok { + return httpErr + } else { + return &HTTPError{http.StatusInternalServerError, err} + } +} + +func IsNotFound(err error) bool { + return HTTPErrorFromError(err).Code == http.StatusNotFound +} + +func HTTPErrorf(code int, format string, a ...interface{}) *HTTPError { + return &HTTPError{code, fmt.Errorf(format, a...)} +} + +func (err *HTTPError) Error() string { + s := fmt.Sprintf("%v %v", err.Code, http.StatusText(err.Code)) + if err.Err != nil { + return fmt.Sprintf("%v: %v", s, err.Err) + } else { + return s + } +} diff --git a/internal/server.go b/internal/server.go index 347aed2..5a51aed 100644 --- a/internal/server.go +++ b/internal/server.go @@ -9,39 +9,6 @@ import ( "strings" ) -type HTTPError struct { - Code int - Err error -} - -func HTTPErrorFromError(err error) *HTTPError { - if err == nil { - return nil - } - if httpErr, ok := err.(*HTTPError); ok { - return httpErr - } else { - return &HTTPError{http.StatusInternalServerError, err} - } -} - -func IsNotFound(err error) bool { - return HTTPErrorFromError(err).Code == http.StatusNotFound -} - -func HTTPErrorf(code int, format string, a ...interface{}) *HTTPError { - return &HTTPError{code, fmt.Errorf(format, a...)} -} - -func (err *HTTPError) Error() string { - s := fmt.Sprintf("%v %v", err.Code, http.StatusText(err.Code)) - if err.Err != nil { - return fmt.Sprintf("%v: %v", s, err.Err) - } else { - return s - } -} - func ServeError(w http.ResponseWriter, err error) { code := http.StatusInternalServerError if httpErr, ok := err.(*HTTPError); ok {