forked from igm/sockjs-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webchat.go
48 lines (42 loc) · 1000 Bytes
/
webchat.go
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
41
42
43
44
45
46
47
48
package main
import (
"log"
"net/http"
"github.com/igm/pubsub"
"github.com/igm/sockjs-go/v3/sockjs"
)
var chat pubsub.Publisher
func main() {
http.Handle("/echo/", sockjs.NewHandler("/echo", sockjs.DefaultOptions, echoHandler))
http.Handle("/", http.FileServer(http.Dir("web/")))
log.Println("Server started on port: 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func echoHandler(session sockjs.Session) {
log.Println("new sockjs session established")
var closedSession = make(chan struct{})
chat.Publish("[info] new participant joined chat")
defer chat.Publish("[info] participant left chat")
go func() {
reader, _ := chat.SubChannel(nil)
for {
select {
case <-closedSession:
return
case msg := <-reader:
if err := session.Send(msg.(string)); err != nil {
return
}
}
}
}()
for {
if msg, err := session.Recv(); err == nil {
chat.Publish(msg)
continue
}
break
}
close(closedSession)
log.Println("sockjs session closed")
}