sessionmanager.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package flowserver
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "sync"
  7. "github.com/gorilla/websocket"
  8. )
  9. //FlowSessionManager or FlowServerCore
  10. type FlowSessionManager struct {
  11. // List of flow sessions?
  12. sessions map[string]*FlowSession
  13. sync.Mutex
  14. }
  15. //New creates a New initialized FlowSessionManager
  16. func New() *FlowSessionManager {
  17. return &FlowSessionManager{
  18. sessions: map[string]*FlowSession{},
  19. }
  20. }
  21. func (fsm *FlowSessionManager) CreateSession() *FlowSession {
  22. fsm.Lock()
  23. defer fsm.Unlock()
  24. for {
  25. ID := RandString(10)
  26. sess, ok := fsm.sessions[ID]
  27. if !ok {
  28. fsm.sessions[ID] = sess
  29. return sess
  30. }
  31. }
  32. }
  33. //LoadSession loads or creates a new Session
  34. func (fsm *FlowSessionManager) LoadSession(ID string) *FlowSession {
  35. fsm.Lock()
  36. defer fsm.Unlock()
  37. log.Println("Fetching session:", ID)
  38. sess, ok := fsm.sessions[ID]
  39. if !ok {
  40. sess = &FlowSession{ID: ID}
  41. fsm.sessions[ID] = sess
  42. }
  43. return sess
  44. }
  45. // FlowMessage Main message structure
  46. type FlowMessage struct {
  47. OP string `json:"op"`
  48. Data json.RawMessage `json:"data"`
  49. }
  50. var upgrader = websocket.Upgrader{}
  51. func (fsm *FlowSessionManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  52. log.Println("Receiving ws connection")
  53. c, err := upgrader.Upgrade(w, r, nil)
  54. if err != nil {
  55. log.Println("upgrade:", err)
  56. }
  57. defer c.Close()
  58. /////////////////
  59. // Message handling
  60. // ////////
  61. for {
  62. mt, data, err := c.ReadMessage()
  63. if err != nil {
  64. log.Println("Err:", err)
  65. break
  66. }
  67. if mt != websocket.TextMessage {
  68. log.Println("Not a text message?")
  69. break
  70. }
  71. fmsg := FlowMessage{}
  72. err = json.Unmarshal(data, &fmsg)
  73. if err != nil {
  74. log.Println("Err parsing message:", err)
  75. c.WriteJSON("bye")
  76. }
  77. switch fmsg.OP {
  78. case "newSession":
  79. log.Println("We want a new session so")
  80. sess := fsm.LoadSession("")
  81. sess.clients = append(sess.clients, c)
  82. }
  83. // Create a Session, assign us to session
  84. // Switch kind of mesasge etc here
  85. // Acquire session ID, and send all the info
  86. // Write msg
  87. // Create or Load a session
  88. }
  89. log.Println("ws Is disconnecting")
  90. }