contact.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package controllers
  2. import (
  3. "cc-officialweb/models"
  4. "cc-officialweb/unity"
  5. "encoding/json"
  6. beego "github.com/beego/beego/v2/server/web"
  7. "github.com/go-playground/validator/v10"
  8. "strconv"
  9. )
  10. type ContactController struct {
  11. beego.Controller
  12. }
  13. func (c *ContactController) Get() {
  14. c.Data["IsContact"] = true
  15. c.TplName = "contact.html"
  16. }
  17. // AddContact 提交联系我们信息
  18. func (c *ContactController) AddContact() {
  19. var contact models.Contact
  20. name := c.GetString("name")
  21. phone := c.GetString("phone")
  22. message := c.GetString("message")
  23. validate := validator.New()
  24. err2 := validate.Var(name, "required")
  25. err2 = validate.Var(phone, "required")
  26. err2 = validate.Var(message, "required")
  27. if err2 != nil {
  28. c.Data["json"] = &JSON{Code: 102, Msg: "添加失败"}
  29. c.ServeJSON()
  30. return
  31. }
  32. contact.Name = name
  33. contact.Phone = phone
  34. contact.Message = message
  35. add, err := unity.Add(&contact)
  36. if err != nil {
  37. c.Data["json"] = &JSON{Code: 102, Msg: "添加失败"}
  38. c.ServeJSON()
  39. return
  40. } else {
  41. c.Data["json"] = &JSON{Code: 200, Msg: "添加成功", Data: add}
  42. c.ServeJSON()
  43. }
  44. }
  45. // DeleteContactById 根据id删除联系消息
  46. func (c *ContactController) DeleteContactById() {
  47. id := c.GetString("id")
  48. atoi, _ := strconv.Atoi(id)
  49. validate := validator.New()
  50. err2 := validate.Var(atoi, "required")
  51. if err2 != nil {
  52. c.Data["json"] = &JSON{Code: 103, Msg: "id不能为空"}
  53. c.ServeJSON()
  54. return
  55. }
  56. _, err := unity.DeleteById(atoi, models.Contact{})
  57. if err != nil {
  58. c.Data["json"] = map[string]interface{}{"code": 101, "msg": "删除失败"}
  59. c.ServeJSON()
  60. return
  61. } else {
  62. c.Data["json"] = map[string]interface{}{"code": 200, "msg": "删除成功"}
  63. c.ServeJSON()
  64. }
  65. }
  66. // GetAllContact 获取所有联系方式
  67. func (c *ContactController) GetAllContact() {
  68. var page unity.PageParams
  69. err := json.Unmarshal(c.Ctx.Input.RequestBody, &page)
  70. if err != nil {
  71. c.Data["json"] = &JSON{Code: 101, Msg: "参数错误"}
  72. c.ServeJSON()
  73. return
  74. }
  75. result, total, current, err := unity.Paginate(page, models.Contact{})
  76. if err != nil {
  77. c.Data["json"] = &JSON{Code: 101, Msg: "查询失败"}
  78. c.ServeJSON()
  79. return
  80. } else {
  81. c.Data["json"] = &JSON{Code: 200, Msg: "查询成功", Data: &JSONS{
  82. Current: current,
  83. Size: total,
  84. Data: result,
  85. }}
  86. c.ServeJSON()
  87. return
  88. }
  89. }