2021-07-13 23:01:31 +08:00
|
|
|
// 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 (
|
2022-03-08 11:50:23 +08:00
|
|
|
"net/http"
|
|
|
|
|
2021-10-11 21:41:56 +08:00
|
|
|
"github.com/gogf/gf/v2/errors/gcode"
|
|
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
|
|
|
"github.com/gogf/gf/v2/internal/intlog"
|
2021-07-13 23:01:31 +08:00
|
|
|
)
|
|
|
|
|
2021-07-19 20:06:44 +08:00
|
|
|
type DefaultHandlerResponse struct {
|
2022-02-17 15:47:08 +08:00
|
|
|
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"`
|
2021-07-19 20:06:44 +08:00
|
|
|
}
|
|
|
|
|
2021-07-13 23:01:31 +08:00
|
|
|
// MiddlewareHandlerResponse is the default middleware handling handler response object and its error.
|
|
|
|
func MiddlewareHandlerResponse(r *Request) {
|
|
|
|
r.Middleware.Next()
|
2021-10-02 22:34:39 +08:00
|
|
|
|
|
|
|
// There's custom buffer content, it then exits current handler.
|
|
|
|
if r.Response.BufferLength() > 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-07-19 20:06:44 +08:00
|
|
|
var (
|
2022-03-08 11:50:23 +08:00
|
|
|
msg string
|
|
|
|
ctx = r.Context()
|
|
|
|
err = r.GetError()
|
|
|
|
res = r.GetHandlerResponse()
|
|
|
|
code = gerror.Code(err)
|
2021-07-19 20:06:44 +08:00
|
|
|
)
|
2021-07-13 23:01:31 +08:00
|
|
|
if err != nil {
|
2021-08-24 21:18:59 +08:00
|
|
|
if code == gcode.CodeNil {
|
|
|
|
code = gcode.CodeInternalError
|
2021-07-20 23:02:02 +08:00
|
|
|
}
|
2022-03-08 11:50:23 +08:00
|
|
|
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
|
2021-07-19 20:06:44 +08:00
|
|
|
}
|
2022-03-08 11:50:23 +08:00
|
|
|
} else {
|
|
|
|
code = gcode.CodeOK
|
2021-07-13 23:01:31 +08:00
|
|
|
}
|
2022-03-08 11:50:23 +08:00
|
|
|
internalErr := r.Response.WriteJson(DefaultHandlerResponse{
|
|
|
|
Code: code.Code(),
|
|
|
|
Message: msg,
|
2021-07-19 20:06:44 +08:00
|
|
|
Data: res,
|
|
|
|
})
|
|
|
|
if internalErr != nil {
|
2022-01-28 14:51:49 +08:00
|
|
|
intlog.Errorf(ctx, `%+v`, internalErr)
|
2021-07-13 23:01:31 +08:00
|
|
|
}
|
|
|
|
}
|