context.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package frame
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/go-playground/validator/v10"
  5. )
  6. // 重新封装上下文对象
  7. type Context struct {
  8. *gin.Context
  9. }
  10. type Response struct {
  11. Status int `json:"status"` // 返回状态值
  12. Msg string `json:"msg"` //返回的提示语
  13. Data interface{} `json:"data"` //返回数据
  14. }
  15. func (this *Context) Success(data ...interface{}) interface{} {
  16. response := Response{
  17. Status: 200,
  18. Msg: "操作成功",
  19. Data: nil,
  20. }
  21. for _, datum := range data {
  22. switch datum.(type) {
  23. case string:
  24. response.Msg = datum.(string)
  25. case interface{}:
  26. response.Data = datum.(interface{})
  27. }
  28. }
  29. return response
  30. }
  31. func (this *Context) Ok(data ...interface{}) {
  32. response := Response{
  33. Status: 200,
  34. Msg: "操作成功",
  35. Data: nil,
  36. }
  37. for _, datum := range data {
  38. switch datum.(type) {
  39. case string:
  40. response.Msg = datum.(string)
  41. case interface{}:
  42. response.Data = datum.(interface{})
  43. }
  44. }
  45. this.JSON(200, response)
  46. }
  47. const FAST_BODY_COLNUM = "fast_body_colnum"
  48. func (this *Context) Cols() []string {
  49. cols, bl := this.Get(FAST_BODY_COLNUM)
  50. /* rts := make([]string, 0)*/
  51. if bl {
  52. /*old := cols.([]string)
  53. for i := 0; i < st.NumField(); i++ {
  54. if collection.Collect(old).Contains(st.Field(i).Name) {
  55. rts = append(rts, st.Field(i).Name)
  56. }
  57. }
  58. return rts*/
  59. return cols.([]string)
  60. }
  61. return make([]string, 0)
  62. }
  63. func (this *Context) Error(data ...interface{}) {
  64. response := Response{
  65. Status: BUSINESS_CODE,
  66. Msg: "操作失败",
  67. Data: nil,
  68. }
  69. for _, datum := range data {
  70. switch datum.(type) {
  71. case string:
  72. response.Msg = datum.(string)
  73. case interface{}:
  74. response.Data = datum.(interface{})
  75. }
  76. }
  77. this.JSON(200, response)
  78. }
  79. func (this *Context) ValidteError(err error, req interface{}) {
  80. if err != nil {
  81. Throw(BUSINESS_CODE, GetError(err.(validator.ValidationErrors), req))
  82. }
  83. }