Browse Source

1.add HTTPError;2.rename ParseParamSuccess to ParseParamFail

Paul 6 years ago
parent
commit
22c5d8a737
2 changed files with 13 additions and 7 deletions
  1. 5
    0
      request/error.go
  2. 8
    7
      request/request.go

+ 5
- 0
request/error.go View File

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

+ 8
- 7
request/request.go View File

4
 	"net/http"
4
 	"net/http"
5
 	"runtime"
5
 	"runtime"
6
 
6
 
7
+	"fmt"
7
 	"github.com/gin-gonic/gin"
8
 	"github.com/gin-gonic/gin"
8
 	"github.com/sirupsen/logrus"
9
 	"github.com/sirupsen/logrus"
9
 )
10
 )
12
 	Check() error
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
 	if r != nil {
17
 	if r != nil {
17
 		if Fail(ctx, http.StatusBadRequest, ctx.ShouldBind(r)) {
18
 		if Fail(ctx, http.StatusBadRequest, ctx.ShouldBind(r)) {
18
-			return false
19
+			return true
19
 		}
20
 		}
20
 
21
 
21
 		if checker, ok := r.(Checker); ok {
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
 	for _, f := range fs {
27
 	for _, f := range fs {
27
 		if Fail(ctx, http.StatusBadRequest, f()) {
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
 func Fail(ctx *gin.Context, status int, err error) bool {
36
 func Fail(ctx *gin.Context, status int, err error) bool {
37
 		return false
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
 	if status == http.StatusInternalServerError {
43
 	if status == http.StatusInternalServerError {
43
 		_, file, line, _ := runtime.Caller(1)
44
 		_, file, line, _ := runtime.Caller(1)
59
 	case "POST":
60
 	case "POST":
60
 		ctx.JSON(http.StatusCreated, data)
61
 		ctx.JSON(http.StatusCreated, data)
61
 	default:
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
 }