-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
ghttp_middleware_handler_response.go
67 lines (59 loc) · 1.75 KB
/
ghttp_middleware_handler_response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp
import (
"net/http"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
)
// DefaultHandlerResponse is the default implementation of HandlerResponse.
type DefaultHandlerResponse struct {
Code int `json:"code" dc:"Error code"`
Message string `json:"message" dc:"Error message"`
Data interface{} `json:"data" dc:"Result data for certain request according API definition"`
}
// MiddlewareHandlerResponse is the default middleware handling handler response object and its error.
func MiddlewareHandlerResponse(r *Request) {
r.Middleware.Next()
// There's custom buffer content, it then exits current handler.
if r.Response.BufferLength() > 0 {
return
}
var (
msg string
err = r.GetError()
res = r.GetHandlerResponse()
code = gerror.Code(err)
)
if err != nil {
if code == gcode.CodeNil {
code = gcode.CodeInternalError
}
msg = err.Error()
} else {
if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
msg = http.StatusText(r.Response.Status)
switch r.Response.Status {
case http.StatusNotFound:
code = gcode.CodeNotFound
case http.StatusForbidden:
code = gcode.CodeNotAuthorized
default:
code = gcode.CodeUnknown
}
// It creates error as it can be retrieved by other middlewares.
err = gerror.NewCode(code, msg)
r.SetError(err)
} else {
code = gcode.CodeOK
}
}
r.Response.WriteJson(DefaultHandlerResponse{
Code: code.Code(),
Message: msg,
Data: res,
})
}