api.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package desktop
  2. import (
  3. "context"
  4. "encoding/json"
  5. "github.com/astaxie/beego/logs"
  6. "nginx-ui/server/models"
  7. "nginx-ui/server/modules/user"
  8. )
  9. var ApiSession = Session{}
  10. var userService = user.NewUserService()
  11. var nginxApi = NewNginxApi()
  12. // Api struct
  13. type Api struct {
  14. ctx context.Context
  15. }
  16. // NewApi NewApp creates a new App application struct
  17. func NewApi() *Api {
  18. return &Api{}
  19. }
  20. // Startup is called when the app starts. The context is saved
  21. // so we can call the runtime methods
  22. func (a *Api) Startup(ctx context.Context) {
  23. ApiSession.ctx = ctx
  24. a.ctx = ctx
  25. ApiSession.Load()
  26. logs.Info("Startup finish")
  27. }
  28. type ApiResp struct {
  29. Data *models.RespData `json:"data"`
  30. }
  31. // PostApi 做一个统一的适配层
  32. func (a *Api) PostApi(path string, req string) ApiResp {
  33. logs.Info("[POST] path: %s, data: %s", path, req)
  34. if nginxApi.Match(path) {
  35. return nginxApi.PostApi(path, req)
  36. }
  37. var data *models.RespData
  38. switch path {
  39. case "/user/login":
  40. var user *models.User
  41. err := json.Unmarshal([]byte(req), user)
  42. if err != nil {
  43. logs.Error(err, req)
  44. data = models.NewErrorResp(err)
  45. }
  46. data = userService.Login(user)
  47. if data.Success() {
  48. ApiSession.SetUser(user)
  49. }
  50. break
  51. case "/user/register":
  52. data = userService.SignUp([]byte(req))
  53. break
  54. }
  55. return ApiResp{Data: data}
  56. }
  57. func (a *Api) GetApi(path string, req string) ApiResp {
  58. logs.Info("[GET] path: %s, data: %s", path, req)
  59. if nginxApi.Match(path) {
  60. return nginxApi.GetApi(path, req)
  61. }
  62. var data *models.RespData
  63. switch path {
  64. case "/user/info":
  65. data = models.SuccessResp(ApiSession.user)
  66. break
  67. }
  68. logs.Info("resp:{}", data)
  69. return ApiResp{Data: data}
  70. }
  71. func (a *Api) DeleteApi(path string, req string) ApiResp {
  72. logs.Info("[DELETE] path: %s, data: %s", path, req)
  73. if nginxApi.Match(path) {
  74. return nginxApi.DeleteApi(path, req)
  75. }
  76. return ApiResp{}
  77. }
  78. func (a *Api) PutApi(path string, req string) ApiResp {
  79. logs.Info("[PUT] path: %s, data: %s", path, req)
  80. if nginxApi.Match(path) {
  81. return nginxApi.PutApi(path, req)
  82. }
  83. return ApiResp{}
  84. }