application.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package application
  2. import (
  3. "context"
  4. "time"
  5. "git.ali33.ru/fcg-xvii/rest"
  6. "git.ali33.ru/fcg-xvii/rest/rest_http"
  7. "git.ali33.ru/fcg-xvii/rest/rest_websocket"
  8. )
  9. func New(appConf *AppConfig, swaggerConf *SwaggerConf, ctx context.Context) rest.IApplication {
  10. app := &Application{
  11. conf: appConf,
  12. //Sockets: NewSockets(),
  13. }
  14. if swaggerConf != nil && swaggerConf.Enabled {
  15. app.swagger = NewSwagger(swaggerConf)
  16. go app.swagger.Start(ctx)
  17. }
  18. go app.start(ctx)
  19. return app
  20. }
  21. type Application struct {
  22. *Sockets
  23. conf *AppConfig
  24. swagger *Swagger
  25. //core any
  26. ctx context.Context
  27. cancel context.CancelFunc
  28. chConnect chan rest.IStream
  29. }
  30. func (s *Application) start(ctx context.Context) (err error) {
  31. s.ctx, s.cancel = context.WithCancel(ctx)
  32. var server rest.IServer
  33. if s.conf.SSL {
  34. server = rest.NewServerTLS(s.conf.Addr, s.conf.Secret, s.conf.TLSKeyPath, s.conf.TLSCertPath)
  35. } else {
  36. server = rest.NewServer(s.conf.Addr, s.conf.Secret)
  37. }
  38. if s.conf.Http {
  39. restServ := rest_http.New(s, s.conf.Core, s.conf.GetHTTPHeaders()())
  40. restServ.Prepare(server, s.conf.GetHttpPrefix())
  41. if s.conf.HttpHandlers != nil {
  42. for prefix, handler := range s.conf.HttpHandlers {
  43. server.HandleFunc(prefix, handler)
  44. }
  45. }
  46. }
  47. if s.conf.Websocket {
  48. s.chConnect = make(chan rest.IStream)
  49. ws := rest_websocket.New(s, s.conf.Core)
  50. ws.Prepare(server, s.conf.GetWebsocketPrefix())
  51. s.Sockets = NewSockets()
  52. go s.work()
  53. }
  54. if err = server.Listen(time.Second, s.ctx); err != nil {
  55. s.cancel()
  56. }
  57. return
  58. }
  59. func (s *Application) Stop() {
  60. s.cancel()
  61. }
  62. func (s *Application) Executer(r rest.IRequestIn) (rest.IExecuter, bool) {
  63. method := s.conf.GetCommandsMethod()
  64. if command, check := method(r.RCommand()); check {
  65. return command, true
  66. }
  67. return nil, false
  68. }