application.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package main
  2. import (
  3. "log"
  4. "os"
  5. "time"
  6. "git.ali33.ru/fcg-xvii/net/v3/http/engine"
  7. "github.com/gorilla/websocket"
  8. )
  9. func NewWSEngine(base engine.Engine, urlPath string) *WSEngine {
  10. res := &WSEngine{
  11. Engine: base,
  12. urlPath: urlPath,
  13. clients: NewWSClients(),
  14. listener: make(chan *WSClient),
  15. }
  16. return res
  17. }
  18. type WSEngine struct {
  19. engine.Engine
  20. urlPath string
  21. clients *WSClients
  22. upgrader websocket.Upgrader
  23. listener chan *WSClient
  24. }
  25. func (s *WSEngine) Listener() <-chan *WSClient {
  26. return s.listener
  27. }
  28. func (s *WSEngine) Exec(req *engine.Request, resp *engine.Response) {
  29. if req.URL.Path == s.urlPath {
  30. if conn, err := s.upgrader.Upgrade(resp.ResponseWriter(), req.Request, nil); err == nil {
  31. cl := s.clients.clientConnected(conn)
  32. select {
  33. case s.listener <- cl:
  34. default:
  35. }
  36. }
  37. return
  38. }
  39. s.Engine.Exec(req, resp)
  40. }
  41. /////////////////////////////
  42. func NewApplication(addr string) engine.Engine {
  43. params := map[string]any{
  44. "addr": addr,
  45. }
  46. app := engine.NewEngineBase(params, nil, "html")
  47. wsApp := NewWSEngine(app, "/api")
  48. go func() {
  49. for cl := range wsApp.Listener() {
  50. //log.Println("CL.....", cl)
  51. go func(c *WSClient) {
  52. //log.Println("CL-READ")
  53. for mes := range c.Read() {
  54. log.Println("------>", mes)
  55. messageIncoming(mes)
  56. }
  57. //log.Println("CL-CLOSE")
  58. t := time.NewTimer(time.Second * time.Duration(downTime))
  59. <-t.C
  60. if c.clients.Size() == 0 {
  61. os.Exit(0)
  62. }
  63. }(cl)
  64. }
  65. }()
  66. return wsApp
  67. }
  68. /*
  69. type WebsocketAppChecker struct {
  70. clients *Clients
  71. }
  72. func (s *WebsocketAppChecker) RequestCheck(r *engine.Request) bool {
  73. log.Println("CHECK", r.URL.Path)
  74. return r.URL.Path == "/api"
  75. }
  76. func NewWebsocketApplication(base engine.Engine) engine.Engine {
  77. app := &WebsocketAppChecker{
  78. }
  79. websocketApp := engine.NewWebsocketApplication(app, engine.DefaultUpgrader())
  80. go func() {
  81. for conn := range websocketApp.Listener() {
  82. .clientConnected(conn)
  83. }
  84. }()
  85. websocketEngine := engine.NewEngineWebsocket(
  86. base,
  87. websocketApp,
  88. )
  89. return websocketEngine
  90. //dapp := engine.NewEngineDomainBase(wapp, 302, "anapa-2.lan")
  91. }
  92. */