chat/server.go
stephen mcquay fda6a98f79 initial chat server working
must send messages over javascript console for now
2015-04-05 15:00:11 -07:00

66 lines
1019 B
Go

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()
}
}
}