From db5737e35b10bcf1e29ebdaae303b5dc72c765c6 Mon Sep 17 00:00:00 2001 From: vicanso Date: Sun, 23 Dec 2018 20:03:44 +0800 Subject: [PATCH] feat: adjust http error --- Gopkg.lock | 9 +++++++ Gopkg.toml | 4 +++ cod.go | 4 +-- df.go | 21 +++++++++++++++- error.go | 47 ----------------------------------- error_test.go | 16 ------------ middleware/basic_auth.go | 5 ++-- middleware/basic_auth_test.go | 6 ++--- middleware/body_parser.go | 5 ++-- middleware/responder.go | 7 +++--- middleware/responder_test.go | 4 +-- 11 files changed, 50 insertions(+), 78 deletions(-) delete mode 100644 error.go delete mode 100644 error_test.go diff --git a/Gopkg.lock b/Gopkg.lock index ac84c8a..c0b8e42 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -33,12 +33,21 @@ revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" version = "1.0.1" +[[projects]] + digest = "1:fb7d260cbd3ce035673cee715167fd1974b9760a04ddce403af270de0e96da01" + name = "github.com/vicanso/errors" + packages = ["."] + pruneopts = "UT" + revision = "d4901179c16c2f9df164cc9fa295982b9285db9d" + version = "0.0.2" + [solve-meta] analyzer-name = "dep" analyzer-version = 1 input-imports = [ "github.com/json-iterator/go", "github.com/julienschmidt/httprouter", + "github.com/vicanso/errors", ] solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index e978043..ac6f113 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -36,3 +36,7 @@ [[constraint]] name = "github.com/json-iterator/go" version = "1.1.5" + +[[constraint]] + name = "github.com/vicanso/errors" + version = "0.0.2" diff --git a/cod.go b/cod.go index ba30c0b..78ddd86 100644 --- a/cod.go +++ b/cod.go @@ -1,11 +1,11 @@ package cod import ( - "errors" "net/http" "sync" "github.com/julienschmidt/httprouter" + "github.com/vicanso/errors" ) var ( @@ -230,7 +230,7 @@ func (d *Cod) Error(c *Context, err error) { return } resp := c.Response - he, ok := err.(*HTTPError) + he, ok := err.(*errors.HTTPError) if ok { resp.WriteHeader(he.StatusCode) resp.Write([]byte(he.Error())) diff --git a/df.go b/df.go index 96a4e9b..b3325b0 100644 --- a/df.go +++ b/df.go @@ -1,6 +1,10 @@ package cod -import "net/http" +import ( + "net/http" + + "github.com/vicanso/errors" +) var ( methods = []string{ @@ -13,9 +17,24 @@ var ( http.MethodOptions, http.MethodTrace, } + + // ErrInvalidRedirect invalid redirect + ErrInvalidRedirect = &errors.HTTPError{ + StatusCode: 400, + Message: "invalid redirect", + Category: ErrCategoryCod, + } + // ErrInvalidResponse invalid response(body an status is nil) + ErrInvalidResponse = &errors.HTTPError{ + StatusCode: 500, + Message: "invalid response", + Category: ErrCategoryCod, + } ) const ( + // ErrCategoryCod cod category + ErrCategoryCod = "cod" // HeaderXForwardedFor x-forwarded-for HeaderXForwardedFor = "X-Forwarded-For" // HeaderXRealIp x-real-ip diff --git a/error.go b/error.go deleted file mode 100644 index cac42dd..0000000 --- a/error.go +++ /dev/null @@ -1,47 +0,0 @@ -package cod - -import ( - "fmt" -) - -const ( - // ErrCategoryCod cod category - ErrCategoryCod = "cod" -) - -var ( - // ErrInvalidRedirect invalid redirect error - ErrInvalidRedirect = NewError(400, "invalid redirect", ErrCategoryCod) - // ErrInvalidResponse invalid response(body an status is nil) - ErrInvalidResponse = NewError(500, "invalid response", ErrCategoryCod) -) - -type ( - // HTTPError http error - HTTPError struct { - StatusCode int `json:"statusCode,omitempty"` - Code string `json:"code,omitempty"` - Category string `json:"category,omitempty"` - Message string `json:"message,omitempty"` - Exception bool `json:"exception,omitempty"` - Extra map[string]interface{} `json:"extra,omitempty"` - } -) - -// Error error interface -func (e *HTTPError) Error() string { - str := fmt.Sprintf("status=%d, message=%s", e.StatusCode, e.Message) - if e.Category == "" { - return str - } - return fmt.Sprintf("category=%s, %s", e.Category, str) -} - -// NewError create an error -func NewError(statusCode int, message, category string) *HTTPError { - return &HTTPError{ - StatusCode: statusCode, - Message: message, - Category: category, - } -} diff --git a/error_test.go b/error_test.go deleted file mode 100644 index a64a5ed..0000000 --- a/error_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package cod - -import ( - "testing" -) - -func TestError(t *testing.T) { - err := &HTTPError{ - StatusCode: 400, - Category: "custom", - Message: "error", - } - if err.Error() != "category=custom, status=400, message=error" { - t.Fatalf("get error fail") - } -} diff --git a/middleware/basic_auth.go b/middleware/basic_auth.go index 5ac95e1..7f30a4e 100644 --- a/middleware/basic_auth.go +++ b/middleware/basic_auth.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/vicanso/cod" + "github.com/vicanso/errors" ) const ( @@ -28,8 +29,8 @@ var ( errUnauthorized = getBasicAuthError("unAuthorized", http.StatusUnauthorized) ) -func getBasicAuthError(message string, statusCode int) *cod.HTTPError { - return &cod.HTTPError{ +func getBasicAuthError(message string, statusCode int) *errors.HTTPError { + return &errors.HTTPError{ StatusCode: statusCode, Message: message, Category: errBasicAuthCategory, diff --git a/middleware/basic_auth_test.go b/middleware/basic_auth_test.go index 99fe66d..2cf7eff 100644 --- a/middleware/basic_auth_test.go +++ b/middleware/basic_auth_test.go @@ -49,7 +49,7 @@ func TestBasicAuth(t *testing.T) { resp := httptest.NewRecorder() d.ServeHTTP(resp, req) if resp.Code != http.StatusBadRequest || - resp.Body.String() != "category=cod-basic-auth, status=400, message=illegal base64 data at input byte 0" { + resp.Body.String() != "category=cod-basic-auth, message=illegal base64 data at input byte 0" { t.Fatalf("base64 decode fail error is invalid") } }) @@ -64,14 +64,14 @@ func TestBasicAuth(t *testing.T) { resp := httptest.NewRecorder() d.ServeHTTP(resp, req) if resp.Code != http.StatusUnauthorized || - resp.Body.String() != "category=cod-basic-auth, status=401, message=unAuthorized" { + resp.Body.String() != "category=cod-basic-auth, message=unAuthorized" { t.Fatalf("validate fail error is invalid") } req.Header.Set(cod.HeaderAuthorization, "basic bjph") resp = httptest.NewRecorder() d.ServeHTTP(resp, req) if resp.Code != http.StatusBadRequest || - resp.Body.String() != "category=cod-basic-auth, status=400, message=account is invalid" { + resp.Body.String() != "category=cod-basic-auth, message=account is invalid" { t.Fatalf("validate return error is fail") } }) diff --git a/middleware/body_parser.go b/middleware/body_parser.go index 7fa3827..21aaee5 100644 --- a/middleware/body_parser.go +++ b/middleware/body_parser.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/vicanso/cod" + "github.com/vicanso/errors" ) const ( @@ -75,7 +76,7 @@ func NewBodyParser(config BodyParserConfig) cod.Handler { body, e := ioutil.ReadAll(c.Request.Body) if e != nil { - err = &cod.HTTPError{ + err = &errors.HTTPError{ StatusCode: http.StatusBadRequest, Message: e.Error(), Category: errBodyParserCategory, @@ -83,7 +84,7 @@ func NewBodyParser(config BodyParserConfig) cod.Handler { return } if limit > 0 && len(body) > limit { - err = &cod.HTTPError{ + err = &errors.HTTPError{ StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("requst body is %d bytes, it should be <= %d", len(body), limit), Category: errBodyParserCategory, diff --git a/middleware/responder.go b/middleware/responder.go index 06dd248..d016081 100644 --- a/middleware/responder.go +++ b/middleware/responder.go @@ -5,6 +5,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/vicanso/cod" + "github.com/vicanso/errors" ) var ( @@ -21,12 +22,12 @@ type ( func NewResponder(config ResponderConfig) cod.Handler { return func(c *cod.Context) error { e := c.Next() - var err *cod.HTTPError + var err *errors.HTTPError if e != nil { // 如果出错,尝试转换为HTTPError - he, ok := e.(*cod.HTTPError) + he, ok := e.(*errors.HTTPError) if !ok { - he = &cod.HTTPError{ + he = &errors.HTTPError{ StatusCode: http.StatusInternalServerError, Message: e.Error(), } diff --git a/middleware/responder_test.go b/middleware/responder_test.go index e2a987c..3ced774 100644 --- a/middleware/responder_test.go +++ b/middleware/responder_test.go @@ -1,11 +1,11 @@ package middleware import ( - "errors" "net/http/httptest" "testing" "github.com/vicanso/cod" + "github.com/vicanso/errors" ) func checkResponse(t *testing.T, resp *httptest.ResponseRecorder, code int, data string) { @@ -59,7 +59,7 @@ func TestResponder(t *testing.T) { d := cod.New() d.Use(m) d.GET("/", func(c *cod.Context) error { - return &cod.HTTPError{ + return &errors.HTTPError{ StatusCode: 400, Message: "abc", Category: "custom",