-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (88 loc) · 2.22 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"fmt"
"net/http"
"os"
"html/template"
"log"
"github.com/gorilla/websocket"
)
var (
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
connectedUsers = 0
nameToConnections = make(map[string]*websocket.Conn)
messageChannel = make(chan message)
)
type message struct {
msgType int
name string
msg string
}
func broadcastMessage() {
for {
msg := <-messageChannel
for name, conn := range nameToConnections {
if name != msg.name {
conn.WriteMessage(msg.msgType, []byte(msg.msg))
}
}
}
}
func serveSimplePage(page string) func (writer http.ResponseWriter, request *http.Request) {
return func (writer http.ResponseWriter, request *http.Request) {
template, err := template.ParseFiles(fmt.Sprintf("website/%s", page))
if err != nil {
log.Print("Error parsing template: ", err)
}
err = template.Execute(writer, nil)
if err != nil {
log.Print("Error during executing: ", err)
}
}
}
func chatHandler(writer http.ResponseWriter, request *http.Request) {
name := request.Header.Get("name")
connectedUsers++
if name == "" {
name = fmt.Sprintf("User %d", connectedUsers)
}
conn, err := upgrader.Upgrade(writer, request, nil)
if err != nil {
panic(err)
}
nameToConnections[name] = conn
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(msg))
messageChannel <- message{
msgType: msgType,
name: name,
msg: string(msg),
}
}
}
func GetPort() string {
port := os.Getenv("PORT")
// Set a default port if there is nothing in the environment
if port == "" {
port = "8080"
fmt.Println("INFO: No PORT environment variable detected, defaulting to " + port)
}
return ":" + port
}
func main() {
go broadcastMessage()
http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("./website"))))
http.HandleFunc("/", serveSimplePage("index.html"))
http.HandleFunc("/textChat/chat", chatHandler)
http.HandleFunc("/videoCall", serveSimplePage("videoCall.html"))
http.HandleFunc("/voiceCall", serveSimplePage("voiceCall.html"))
http.HandleFunc("/textChat", serveSimplePage("textChat.html"))
http.ListenAndServe(GetPort(), nil)
}