application.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package application
  2. import (
  3. "baize-demo/project/server/application/service"
  4. "baize-demo/project/server/config"
  5. "git.sxidc.com/go-framework/baize"
  6. "git.sxidc.com/go-framework/baize/framework/core/api"
  7. "git.sxidc.com/go-framework/baize/framework/core/application"
  8. "net/http"
  9. )
  10. var appInstance *application.App
  11. func NewApp() {
  12. if appInstance != nil {
  13. return
  14. }
  15. appInstance = baize.NewApplication(config.GetConfig().ApplicationConfig)
  16. // 注册Router
  17. appInstance.Api().PrefixRouter().RegisterVersionedRouter("v1")
  18. err := appInstance.Infrastructure().LocalCache().Set("version", "v1.0.0", 5)
  19. if err != nil {
  20. panic(err)
  21. }
  22. err = appInstance.Infrastructure().RedisCache().Set("version", "v1.0.0", 5)
  23. if err != nil {
  24. panic(err)
  25. }
  26. }
  27. func DestroyApp() {
  28. if appInstance == nil {
  29. return
  30. }
  31. err := appInstance.Infrastructure().RedisCache().Clear()
  32. if err != nil {
  33. panic(err)
  34. }
  35. err = appInstance.Infrastructure().LocalCache().Clear()
  36. if err != nil {
  37. panic(err)
  38. }
  39. baize.DestroyApplication(appInstance)
  40. appInstance = nil
  41. }
  42. func Start() error {
  43. // 初始化服务
  44. for _, svc := range service.RegisteredServices {
  45. err := svc.Init(appInstance)
  46. if err != nil {
  47. return err
  48. }
  49. }
  50. err := appInstance.Start()
  51. if err != nil {
  52. return err
  53. }
  54. return nil
  55. }
  56. func Finish() error {
  57. err := appInstance.Finish()
  58. if err != nil {
  59. return err
  60. }
  61. // 销毁服务
  62. for _, svc := range service.RegisteredServices {
  63. err := svc.Destroy()
  64. if err != nil {
  65. return err
  66. }
  67. }
  68. return nil
  69. }
  70. func ServerHttpForTest(w http.ResponseWriter, req *http.Request) {
  71. appInstance.Api().RootRouter().(*api.RootRouter).ServerHttp(w, req)
  72. }