Przeglądaj źródła

add http response check

Paul 6 lat temu
rodzic
commit
1963980312
1 zmienionych plików z 90 dodań i 0 usunięć
  1. 90
    0
      middleware/check/check.go

+ 90
- 0
middleware/check/check.go Wyświetl plik

@@ -0,0 +1,90 @@
1
+package check
2
+
3
+import (
4
+	"encoding/json"
5
+	"fmt"
6
+	"github.com/gin-gonic/gin"
7
+	"net/http"
8
+)
9
+
10
+type (
11
+	errorWriter struct {
12
+		gin.ResponseWriter
13
+		data []byte
14
+	}
15
+)
16
+
17
+func (ew *errorWriter) WriteString(data string) (int, error) {
18
+	ew.data = append(ew.data, []byte(data)...)
19
+	return ew.ResponseWriter.WriteString(data)
20
+}
21
+
22
+func (ew *errorWriter) Write(data []byte) (int, error) {
23
+	ew.data = append(ew.data, data...)
24
+
25
+	return ew.ResponseWriter.Write(data)
26
+}
27
+
28
+func (ew *errorWriter) successful() bool {
29
+	switch ew.Status() {
30
+	case 200, 201, 202, 204:
31
+		return true
32
+	case 400, 401, 403, 404, 406, 410, 422, 500:
33
+		return false
34
+	default:
35
+		panic(fmt.Sprintf("unsupported status code %d", ew.Status()))
36
+	}
37
+}
38
+
39
+func CodeAnalysis() gin.HandlerFunc {
40
+	return func(ctx *gin.Context) {
41
+		ew := &errorWriter{ResponseWriter: ctx.Writer}
42
+		ctx.Writer = ew
43
+
44
+		ctx.Next()
45
+
46
+		switch ew.Header().Get("Content-Type") {
47
+		case "application/json; charset=utf-8":
48
+			rps := map[string]string{}
49
+
50
+			err := json.Unmarshal(ew.data, &rps)
51
+			if err != nil {
52
+				panic("unsupported data format, only json now.")
53
+			}
54
+
55
+			if !ew.successful() {
56
+				if len(rps) != 1 || rps["msg"] == "" {
57
+					panic(fmt.Sprintf("you need return %s but, %s", `{"msg":"content can't empty'"}`, string(ew.data)))
58
+				}
59
+			} else {
60
+				// 如果post请求的状态码不是201的话返回错误
61
+				if ctx.Request.Method == "POST" && ew.Status() != http.StatusCreated {
62
+					panic(fmt.Sprintf("you need set http status to %d", http.StatusCreated))
63
+				}
64
+
65
+				// 如果状态码是201但是请求方式不是post的话返回错误
66
+				if ew.Status() == http.StatusCreated && ctx.Request.Method != "POST" {
67
+					panic(fmt.Sprintf("the http status %d can set when method=POST", http.StatusCreated))
68
+				}
69
+
70
+				// 如果返回的数据为nil则报错
71
+				if rps == nil {
72
+					panic(fmt.Sprintf("if response body is null, please only set http status"))
73
+				}
74
+
75
+				// 如果返回状态码为204则body不能有任何数据
76
+				if ew.Status() == http.StatusNoContent && len(ew.data) != 0 {
77
+					panic(fmt.Sprintf("if response stauts is %d, can't have reponse body", http.StatusNoContent))
78
+				}
79
+			}
80
+		default:
81
+			if len(ew.data) == 0 && ew.Status() != http.StatusNoContent {
82
+				panic(fmt.Sprintf("if response body is null, please only set http status %d", http.StatusNoContent))
83
+			}
84
+
85
+			if len(ew.data) != 0 {
86
+				panic("unsupported data format, only json now.")
87
+			}
88
+		}
89
+	}
90
+}