123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- package main
- import (
- "log"
- "os"
- "time"
- "git.ali33.ru/fcg-xvii/net/v3/http/engine"
- "github.com/gorilla/websocket"
- )
- func NewWSEngine(base engine.Engine, urlPath string) *WSEngine {
- res := &WSEngine{
- Engine: base,
- urlPath: urlPath,
- clients: NewWSClients(),
- listener: make(chan *WSClient),
- }
- return res
- }
- type WSEngine struct {
- engine.Engine
- urlPath string
- clients *WSClients
- upgrader websocket.Upgrader
- listener chan *WSClient
- }
- func (s *WSEngine) Listener() <-chan *WSClient {
- return s.listener
- }
- func (s *WSEngine) Exec(req *engine.Request, resp *engine.Response) {
- if req.URL.Path == s.urlPath {
- if conn, err := s.upgrader.Upgrade(resp.ResponseWriter(), req.Request, nil); err == nil {
- cl := s.clients.clientConnected(conn)
- select {
- case s.listener <- cl:
- default:
- }
- }
- return
- }
- s.Engine.Exec(req, resp)
- }
- /////////////////////////////
- func NewApplication(addr string) engine.Engine {
- params := map[string]any{
- "addr": addr,
- }
- app := engine.NewEngineBase(params, nil, "html")
- wsApp := NewWSEngine(app, "/api")
- go func() {
- for cl := range wsApp.Listener() {
- //log.Println("CL.....", cl)
- go func(c *WSClient) {
- //log.Println("CL-READ")
- for mes := range c.Read() {
- log.Println("------>", mes)
- messageIncoming(mes)
- }
- //log.Println("CL-CLOSE")
- t := time.NewTimer(time.Second * time.Duration(downTime))
- <-t.C
- if c.clients.Size() == 0 {
- os.Exit(0)
- }
- }(cl)
- }
- }()
- return wsApp
- }
- /*
- type WebsocketAppChecker struct {
- clients *Clients
- }
- func (s *WebsocketAppChecker) RequestCheck(r *engine.Request) bool {
- log.Println("CHECK", r.URL.Path)
- return r.URL.Path == "/api"
- }
- func NewWebsocketApplication(base engine.Engine) engine.Engine {
- app := &WebsocketAppChecker{
- }
- websocketApp := engine.NewWebsocketApplication(app, engine.DefaultUpgrader())
- go func() {
- for conn := range websocketApp.Listener() {
- .clientConnected(conn)
- }
- }()
- websocketEngine := engine.NewEngineWebsocket(
- base,
- websocketApp,
- )
- return websocketEngine
- //dapp := engine.NewEngineDomainBase(wapp, 302, "anapa-2.lan")
- }
- */
|