package flowserver import ( "encoding/json" "log" "net/http" "sync" "github.com/gorilla/websocket" ) //FlowSessionManager or FlowServerCore type FlowSessionManager struct { // List of flow sessions? sessions map[string]*FlowSession sync.Mutex } //New creates a New initialized FlowSessionManager func New() *FlowSessionManager { return &FlowSessionManager{ sessions: map[string]*FlowSession{}, } } func (fsm *FlowSessionManager) CreateSession() *FlowSession { fsm.Lock() defer fsm.Unlock() for { ID := RandString(10) sess, ok := fsm.sessions[ID] if !ok { fsm.sessions[ID] = sess return sess } } } //LoadSession loads or creates a new Session func (fsm *FlowSessionManager) LoadSession(ID string) *FlowSession { fsm.Lock() defer fsm.Unlock() log.Println("Fetching session:", ID) sess, ok := fsm.sessions[ID] if !ok { sess = &FlowSession{ID: ID} fsm.sessions[ID] = sess } return sess } // FlowMessage Main message structure type FlowMessage struct { OP string `json:"op"` Data json.RawMessage `json:"data"` } var upgrader = websocket.Upgrader{} func (fsm *FlowSessionManager) ServeHTTP(w http.ResponseWriter, r *http.Request) { log.Println("Receiving ws connection") c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("upgrade:", err) } defer c.Close() ///////////////// // Message handling // //////// for { mt, data, err := c.ReadMessage() if err != nil { log.Println("Err:", err) break } if mt != websocket.TextMessage { log.Println("Not a text message?") break } fmsg := FlowMessage{} err = json.Unmarshal(data, &fmsg) if err != nil { log.Println("Err parsing message:", err) c.WriteJSON("bye") } switch fmsg.OP { case "newSession": log.Println("We want a new session so") sess := fsm.LoadSession("") sess.clients = append(sess.clients, c) } // Create a Session, assign us to session // Switch kind of mesasge etc here // Acquire session ID, and send all the info // Write msg // Create or Load a session } log.Println("ws Is disconnecting") }