1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- package application
- import (
- "context"
- "log"
- "sync/atomic"
- "time"
- "git.ali33.ru/fcg-xvii/rest"
- "git.ali33.ru/fcg-xvii/rest/rest_http"
- "git.ali33.ru/fcg-xvii/rest/rest_websocket"
- )
- func New(appConf *AppConfig, swaggerConf *SwaggerConf, ctx context.Context) rest.IApplication {
- app := &Application{
- conf: appConf,
- }
- if swaggerConf != nil && swaggerConf.Enabled {
- app.swagger = NewSwagger(swaggerConf)
- go app.swagger.Start(ctx)
- }
- go app.start(ctx)
- return app
- }
- type Application struct {
- conf *AppConfig
- swagger *Swagger
- //core any
- ctx context.Context
- cancel context.CancelFunc
- chConnect chan rest.IStream
- }
- func (s *Application) start(ctx context.Context) (err error) {
- s.ctx, s.cancel = context.WithCancel(ctx)
- var server rest.IServer
- if s.conf.SSL {
- server = rest.NewServerTLS(s.conf.Addr, s.conf.Secret, s.conf.TLSKeyPath, s.conf.TLSCertPath)
- } else {
- server = rest.NewServer(s.conf.Addr, s.conf.Secret)
- }
- if s.conf.Http {
- restServ := rest_http.New(s, s.conf.Core, s.conf.GetHTTPHeaders()())
- restServ.Prepare(server, s.conf.GetHttpPrefix())
- //log.Println("http part prepared...")
- }
- if s.conf.Websocket {
- s.chConnect = make(chan rest.IStream)
- ws := rest_websocket.New(s, s.conf.Core)
- ws.Prepare(server, s.conf.GetWebsocketPrefix())
- go s.work()
- //log.Println("websocket engine prepared...")
- }
- if err = server.Listen(time.Second, s.ctx); err != nil {
- s.cancel()
- }
- return
- }
- func (s *Application) Stop() {
- s.cancel()
- }
- func (s *Application) work() {
- var counter atomic.Int32
- for {
- select {
- case <-s.ctx.Done():
- return
- case stream := <-s.chConnect:
- log.Println("CONNECT-------", counter.Add(1))
- if s.conf.OnSocketConnect != nil {
- s.conf.OnSocketConnect(stream)
- }
- go func(rStream rest.IStream) {
- <-rStream.Context().Done()
- log.Println("DISCONNECT-------", counter.Add(-1))
- if s.conf.OnSocketDisconnect != nil {
- s.conf.OnSocketDisconnect(rStream)
- }
- }(stream)
- }
- }
- }
- func (s *Application) Executer(r rest.IRequestIn) (rest.IExecuter, bool) {
- log.Println("EXECUTER", r.RCommand())
- if command, check := s.conf.Commands(r.RCommand()); check {
- log.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
- return command, true
- }
- return nil, false
- }
- func (s *Application) Connect() chan<- rest.IStream {
- return s.chConnect
- }
|