response.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. "gof_ppw_api/api"
  7. "net/http"
  8. )
  9. func Response(r *ghttp.Request) {
  10. r.Middleware.Next()
  11. // fmt.Println("using res middleware after..")
  12. // fmt.Println(r.Response.BufferLength())
  13. if r.Response.BufferLength() > 0 {
  14. return
  15. }
  16. var (
  17. msg string
  18. err = r.GetError()
  19. res = r.GetHandlerResponse()
  20. code = gerror.Code(err)
  21. fRes interface{}
  22. )
  23. if err != nil {
  24. if code == gcode.CodeNil {
  25. code = gcode.CodeInternalError
  26. }
  27. msg = err.Error()
  28. fRes = struct{}{}
  29. } else if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
  30. msg = http.StatusText(r.Response.Status)
  31. switch r.Response.Status {
  32. case http.StatusNotFound:
  33. code = gcode.CodeNotFound
  34. case http.StatusForbidden:
  35. code = gcode.CodeNotAuthorized
  36. default:
  37. code = gcode.CodeUnknown
  38. }
  39. fRes = struct{}{}
  40. } else {
  41. code = gcode.CodeOK
  42. if res.(*api.CommonRes) != nil {
  43. fRes = res.(*api.CommonRes).Data
  44. } else {
  45. fRes = struct{}{}
  46. }
  47. }
  48. r.Response.WriteJsonExit(DefaultHandlerResponse{
  49. Code: code.Code(),
  50. Message: msg,
  51. Data: fRes,
  52. })
  53. }