controller.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package proxy
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/astaxie/beego/logs"
  6. "nginx-ui/server/base"
  7. "nginx-ui/server/models"
  8. )
  9. type Controller struct {
  10. base.Controller
  11. service *Service
  12. }
  13. var Proxy = NewReverseProxy()
  14. var Instance = &Controller{
  15. service: NewProxyService(),
  16. }
  17. func (c *Controller) RefreshProxies() {
  18. list := c.service.GetAll(&GetProxyListReq{Enable: true})
  19. Proxy.LoadProxies(list)
  20. }
  21. // List 登录
  22. func (c *Controller) List() {
  23. user := c.RequiredUser()
  24. if user == nil {
  25. return
  26. }
  27. var req GetProxyListReq
  28. err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
  29. if err != nil {
  30. logs.Error(err, string(c.Ctx.Input.RequestBody))
  31. c.ErrorJson(err)
  32. return
  33. }
  34. req.Uid = user.Id
  35. resp := c.service.GetAll(&req)
  36. c.SetData(resp).Json()
  37. }
  38. // Save 获取全部用户信息
  39. func (c *Controller) Save() {
  40. user := c.RequiredUser()
  41. if user == nil {
  42. return
  43. }
  44. req := models.ProxyEntity{}
  45. if !c.ReadBody(&req) {
  46. return
  47. }
  48. if req.Id == 0 {
  49. req.UserId = user.Id
  50. }
  51. resp, err := c.service.Update(&req)
  52. if err != nil {
  53. logs.Warn("Users get fail: %v", err)
  54. c.ErrorJson(err)
  55. return
  56. }
  57. c.RefreshProxies()
  58. c.SetData(resp).Json()
  59. }
  60. // Remove 删除指定的代理
  61. func (c *Controller) Remove() {
  62. user := c.RequiredUser()
  63. if user == nil {
  64. return
  65. }
  66. req := models.ProxyEntity{}
  67. if !c.ReadBody(&req) {
  68. return
  69. }
  70. if req.UserId != user.Id {
  71. c.ErrorJson(errors.New("更新失败,无操作权限!"))
  72. return
  73. }
  74. resp, err := c.service.Delete(&req)
  75. if err != nil {
  76. logs.Warn("Users get fail: %v", err)
  77. c.ErrorJson(err)
  78. return
  79. }
  80. c.SetSession("user", *resp)
  81. c.RefreshProxies()
  82. c.SetData(resp).Json()
  83. }