default.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package controllers
  2. import (
  3. "github.com/astaxie/beego"
  4. "github.com/astaxie/beego/logs"
  5. "nginx-ui/server/middleware"
  6. "nginx-ui/server/models"
  7. "strconv"
  8. )
  9. type BaseController struct {
  10. beego.Controller
  11. jsonData *models.RespData
  12. // json real data
  13. respData map[string]any
  14. }
  15. func (c *BaseController) json() {
  16. c.checkJsonData()
  17. if c.respData != nil {
  18. c.jsonData.Data = c.respData
  19. }
  20. c.Data["json"] = c.jsonData
  21. c.ServeJSON()
  22. }
  23. func (c *BaseController) postJson(json interface{}) {
  24. c.Data["json"] = json
  25. c.ServeJSON()
  26. }
  27. func (c *BaseController) ErrorJson(error error) {
  28. c.setCode(-1).setMsg(error.Error()).json()
  29. }
  30. func (c *BaseController) checkJsonData() *BaseController {
  31. data := c.jsonData
  32. if data == nil {
  33. data = &models.RespData{
  34. Code: 0,
  35. Msg: "success",
  36. Data: nil,
  37. }
  38. c.jsonData = data
  39. }
  40. return c
  41. }
  42. func (c *BaseController) setData(v interface{}) *BaseController {
  43. c.checkJsonData()
  44. c.jsonData.Data = v
  45. return c
  46. }
  47. func (c *BaseController) addRespData(k string, v interface{}) *BaseController {
  48. c.checkJsonData()
  49. if c.respData == nil {
  50. c.respData = map[string]any{}
  51. }
  52. c.respData[k] = v
  53. return c
  54. }
  55. func (c *BaseController) setCode(code int) *BaseController {
  56. c.checkJsonData()
  57. c.jsonData.Code = code
  58. return c
  59. }
  60. func (c *BaseController) setMsg(msg string) *BaseController {
  61. c.checkJsonData()
  62. c.jsonData.Msg = msg
  63. return c
  64. }
  65. func (c *BaseController) getParam(k string) string {
  66. return c.Ctx.Input.Param(k)
  67. }
  68. func (c *BaseController) getIntParam(k string) (int, error) {
  69. idStr := c.Ctx.Input.Param(k)
  70. id, err := strconv.Atoi(idStr)
  71. logs.Info("id", id)
  72. if err != nil {
  73. return 0, err
  74. }
  75. return id, nil
  76. }
  77. func (c *BaseController) GetUser(required bool) *models.User {
  78. data := c.GetSession("user")
  79. if data == nil && required {
  80. middleware.WriteForbidden(c.Ctx.ResponseWriter)
  81. return nil
  82. }
  83. if data == nil {
  84. return nil
  85. }
  86. user := data.(models.User)
  87. return &user
  88. }
  89. func (c *BaseController) RequiredUser() *models.User {
  90. return c.GetUser(true)
  91. }
  92. func (c *BaseController) Forbidden() {
  93. c.setCode(403).setMsg("您没有权限操作该实例!").json()
  94. }