initial chat server working
must send messages over javascript console for now
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/op/go-logging"
|
||||
)
|
||||
|
||||
var logs *logging.Logger
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
logs, err = logging.GetLogger("server")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
type success struct {
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type failure struct {
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func NewFailure(msg string) *failure {
|
||||
return &failure{
|
||||
Success: false,
|
||||
Error: msg,
|
||||
}
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ulock sync.Mutex
|
||||
users map[string]*user
|
||||
chatter chan string
|
||||
}
|
||||
|
||||
func NewChat(sm *http.ServeMux, static string) (*Chat, error) {
|
||||
chat := &Chat{
|
||||
users: make(map[string]*user),
|
||||
chatter: make(chan string),
|
||||
}
|
||||
addRoutes(sm, chat, static)
|
||||
go chat.Sender()
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *Chat) Sender() {
|
||||
for {
|
||||
select {
|
||||
case msg := <-c.chatter:
|
||||
c.ulock.Lock()
|
||||
logs.Debug("got message: %q", msg)
|
||||
for name, user := range c.users {
|
||||
logs.Debug("\tsending %s: %q", name, msg)
|
||||
user.send <- msg
|
||||
}
|
||||
c.ulock.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user