1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package controllers
  2. import (
  3. "net/http"
  4. "support-game/utils"
  5. "github.com/astaxie/beego"
  6. "github.com/astaxie/beego/config"
  7. )
  8. //BaseController 基础controller
  9. type BaseController struct {
  10. beego.Controller
  11. Context *utils.Context
  12. Configer map[string]config.Configer
  13. RunMode string
  14. }
  15. //Prepare 继承beego的
  16. func (c *BaseController) Prepare() {
  17. // 读取配置文件
  18. c.initConfig()
  19. // 初始化上下文
  20. c.initContext()
  21. // 路由对应的实际 Controller 初始化
  22. c.initController()
  23. }
  24. // ResponseJSON 返回JSON数据
  25. func (c *BaseController) ResponseJSON(data interface{}) {
  26. c.ResponseData(data, "", http.StatusOK)
  27. }
  28. // ResponseError 返回错误
  29. func (c *BaseController) ResponseError(err error, code ...int) {
  30. if len(code) > 0 {
  31. c.ResponseData(nil, err, code[0])
  32. }
  33. c.ResponseData(nil, err, http.StatusBadRequest)
  34. }
  35. // ResponseRaw 返回
  36. func (c *BaseController) ResponseRaw(msg []byte, stop ...bool) {
  37. c.Ctx.ResponseWriter.Write(msg)
  38. if stop != nil && len(stop) > 0 {
  39. if !stop[0] {
  40. return
  41. }
  42. }
  43. c.destroyContext(true)
  44. c.StopRun()
  45. }
  46. // ResponseData 自定义的JSON返回
  47. func (c *BaseController) ResponseData(data interface{}, msg interface{}, code int) {
  48. status := code
  49. sendMessage := ""
  50. switch msgVal := msg.(type) {
  51. case error:
  52. sendMessage = msgVal.Error()
  53. case string:
  54. sendMessage = msgVal
  55. default:
  56. sendMessage = ""
  57. }
  58. c.Data["json"] = JSONMessage{status, sendMessage, data}
  59. c.destroyContext(status < http.StatusMultipleChoices)
  60. c.crosPolicy()
  61. c.ServeJSON()
  62. c.StopRun()
  63. }
  64. // initAppController 执行当前路由请求对应的 Controller 初始化
  65. func (c *BaseController) initController() {
  66. if ctrl, ok := c.AppController.(ControllerInterface); ok {
  67. ctrl.Constructor()
  68. }
  69. }