Skip to content

Instantly share code, notes, and snippets.

@apokalyptik
Created June 18, 2014 19:11
Show Gist options
  • Save apokalyptik/0285a7ba93729d63fbdb to your computer and use it in GitHub Desktop.
Save apokalyptik/0285a7ba93729d63fbdb to your computer and use it in GitHub Desktop.
Simple chat server in go
package main
import (
"log"
"net/http"
"code.google.com/p/go.net/websocket"
)
type register struct {
out chan string
reply chan int
}
var enter = make(chan register)
var exit = make(chan int)
var say = make(chan string)
func mindChatServer() {
var users = make(map[int]chan string)
var userID = 0
for {
select {
case m := <-enter:
users[userID] = m.out
m.reply <- userID
userID++
case m := <-say:
for _, user := range users {
user <- m
}
case m := <-exit:
delete(users, m)
}
}
}
func mindClient(ws *websocket.Conn) {
var uidChan = make(chan int)
var outChan = make(chan string)
var errChan = make(chan struct{})
enter <- register{out: outChan, reply: uidChan}
uid := <-uidChan
close(uidChan)
defer func() {
exit <- uid
close(errChan)
}()
go func() {
for {
select {
case m := <-outChan:
websocket.Message.Send(ws, m)
case <-errChan:
close(outChan)
return
}
}
}()
for {
var message string
if err := websocket.Message.Receive(ws, &message); err != nil {
return
}
say <- message
}
}
func main() {
go mindChatServer()
http.Handle("/", websocket.Handler(mindClient))
if err := http.ListenAndServe(":12345", nil); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment