Parcourir la source

1.add HTTPError;2.rename ParseParamSuccess to ParseParamFail

Paul il y a 6 ans
Parent
révision
22c5d8a737
2 fichiers modifiés avec 13 ajouts et 7 suppressions
  1. 5
    0
      request/error.go
  2. 8
    7
      request/request.go

+ 5
- 0
request/error.go Voir le fichier

@@ -0,0 +1,5 @@
1
+package request
2
+
3
+type HTTPError struct {
4
+	Msg string `json:"msg" example:"status bad request"`
5
+}

+ 8
- 7
request/request.go Voir le fichier

@@ -4,6 +4,7 @@ import (
4 4
 	"net/http"
5 5
 	"runtime"
6 6
 
7
+	"fmt"
7 8
 	"github.com/gin-gonic/gin"
8 9
 	"github.com/sirupsen/logrus"
9 10
 )
@@ -12,24 +13,24 @@ type Checker interface {
12 13
 	Check() error
13 14
 }
14 15
 
15
-func ParseParamSuccess(ctx *gin.Context, r interface{}, fs ...func() error) bool {
16
+func ParseParamFail(ctx *gin.Context, r interface{}, fs ...func() error) bool {
16 17
 	if r != nil {
17 18
 		if Fail(ctx, http.StatusBadRequest, ctx.ShouldBind(r)) {
18
-			return false
19
+			return true
19 20
 		}
20 21
 
21 22
 		if checker, ok := r.(Checker); ok {
22
-			return !Fail(ctx, http.StatusBadRequest, checker.Check())
23
+			return Fail(ctx, http.StatusBadRequest, checker.Check())
23 24
 		}
24 25
 	}
25 26
 
26 27
 	for _, f := range fs {
27 28
 		if Fail(ctx, http.StatusBadRequest, f()) {
28
-			return false
29
+			return true
29 30
 		}
30 31
 	}
31 32
 
32
-	return true
33
+	return false
33 34
 }
34 35
 
35 36
 func Fail(ctx *gin.Context, status int, err error) bool {
@@ -37,7 +38,7 @@ func Fail(ctx *gin.Context, status int, err error) bool {
37 38
 		return false
38 39
 	}
39 40
 
40
-	ctx.JSON(status, gin.H{"msg": err.Error()})
41
+	ctx.JSON(status, HTTPError{Msg: err.Error()})
41 42
 
42 43
 	if status == http.StatusInternalServerError {
43 44
 		_, file, line, _ := runtime.Caller(1)
@@ -59,6 +60,6 @@ func Success(ctx *gin.Context, data interface{}) {
59 60
 	case "POST":
60 61
 		ctx.JSON(http.StatusCreated, data)
61 62
 	default:
62
-		ctx.JSON(http.StatusBadRequest, gin.H{"msg": "unsupported request method" + ctx.Request.Method})
63
+		ctx.JSON(http.StatusBadRequest, HTTPError{Msg: fmt.Sprintf("unsupported request method %s", ctx.Request.Method)})
63 64
 	}
64 65
 }