Init
This commit is contained in:
commit
508a04cf4c
30 changed files with 1545 additions and 0 deletions
76
session.go
Normal file
76
session.go
Normal file
|
@ -0,0 +1,76 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
|
||||
"github.com/khlieng/irc/storage"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
irc map[string]*IRC
|
||||
ircLock sync.Mutex
|
||||
|
||||
ws map[string]*WebSocket
|
||||
wsLock sync.Mutex
|
||||
out chan []byte
|
||||
|
||||
user storage.User
|
||||
}
|
||||
|
||||
func NewSession() *Session {
|
||||
return &Session{
|
||||
irc: make(map[string]*IRC),
|
||||
ws: make(map[string]*WebSocket),
|
||||
out: make(chan []byte, 32),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) getIRC(server string) (*IRC, bool) {
|
||||
s.ircLock.Lock()
|
||||
defer s.ircLock.Unlock()
|
||||
|
||||
irc, ok := s.irc[server]
|
||||
return irc, ok
|
||||
}
|
||||
|
||||
func (s *Session) setIRC(server string, irc *IRC) {
|
||||
s.ircLock.Lock()
|
||||
s.irc[server] = irc
|
||||
s.ircLock.Unlock()
|
||||
}
|
||||
|
||||
func (s *Session) setWS(addr string, ws *websocket.Conn) {
|
||||
socket := NewWebSocket(ws)
|
||||
go socket.write()
|
||||
|
||||
s.wsLock.Lock()
|
||||
s.ws[addr] = socket
|
||||
s.wsLock.Unlock()
|
||||
}
|
||||
|
||||
func (s *Session) deleteWS(addr string) {
|
||||
s.wsLock.Lock()
|
||||
delete(s.ws, addr)
|
||||
s.wsLock.Unlock()
|
||||
}
|
||||
|
||||
func (s *Session) sendJSON(t string, v interface{}) {
|
||||
data, _ := json.Marshal(v)
|
||||
raw := json.RawMessage(data)
|
||||
res, _ := json.Marshal(WSResponse{Type: t, Response: &raw})
|
||||
|
||||
s.out <- res
|
||||
}
|
||||
|
||||
func (s *Session) write() {
|
||||
for res := range s.out {
|
||||
s.wsLock.Lock()
|
||||
for _, ws := range s.ws {
|
||||
ws.In <- res
|
||||
}
|
||||
s.wsLock.Unlock()
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue