summaryrefslogtreecommitdiff
path: root/websock.go
blob: a72bf8c8b6aaa63db3ef65df1ca61f0c3a8a8113 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main

import (
	"code.google.com/p/go.net/websocket"
	"github.com/gorilla/mux"
	"log"
	"net/http"
)

func AcceptWebSock(rw http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	room := vars["chatroom"]
	websocket.Handler(func(ws *websocket.Conn) {
		defer ws.Close()

		var nick string
		if websocket.Message.Receive(ws, &nick) != nil {
			return
		}

		if err := Join(room, nick); err != nil {
			// TODO: report error to client
			return
		}

		usermsgs := make(chan string)
		go func() {
			var s string
			for {
				if websocket.Message.Receive(ws, &s) != nil {
					return
				}

				if s != "" {
					usermsgs <- s
				}
			}
		}()
	}).ServeHTTP(rw, req)
}