-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
67 lines (54 loc) · 1.48 KB
/
main.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"fmt"
"html/template"
"net/http"
"time"
dotEnv "github.com/joho/godotenv"
websockethandler "github.com/brianwu291/go-playground/handlers/websocket"
realtimechat "github.com/brianwu291/go-playground/realtimechat"
utils "github.com/brianwu291/go-playground/utils"
)
type ChatTemplateEnvs struct {
WebSocketUrl string
}
func serveChat(w http.ResponseWriter, r *http.Request) {
data := ChatTemplateEnvs{
WebSocketUrl: utils.GetEnv("WEBSOCKETURL", "ws://localhost:8080"),
}
tmpl, err := template.ParseFiles("templates/chat.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl.Execute(w, data)
}
func manageRoomLifecycle(rt *realtimechat.RealTimeChat) {
for {
// sleep for 1.5 hours between cleanup cycles
time.Sleep(90 * time.Minute)
rooms := rt.ListRooms()
for _, roomName := range rooms {
if room, err := rt.GetRoom(roomName); err == nil {
room.Stop()
}
}
}
}
func main() {
err := dotEnv.Load()
if err != nil {
fmt.Printf("error loading .env file: %+v", err.Error())
return
}
// init without max clients as it's per room now
chat := realtimechat.NewRealTimeChat()
// start room lifecycle management
go manageRoomLifecycle(chat)
wsh := websockethandler.NewWebSocketHandler(chat)
http.HandleFunc("/ws", wsh.HandleRealTimeChat)
http.HandleFunc("/", serveChat)
portStr := utils.GetEnv("PORT", "8080")
fmt.Printf("listening port %+v\n", portStr)
http.ListenAndServe(":"+portStr, nil)
}