resMiddleware.go 1.9 KB

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