-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
80 lines (64 loc) · 1.71 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
package main
import (
"flag"
"log"
"net/http"
"path/filepath"
"strings"
"sync"
"text/template"
"github.com/comail/colog"
"github.com/gorilla/mux"
)
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
type roomSettings struct {
Host string
Name string
}
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
name := params["name"]
t.once.Do(func() {
t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
})
if strings.HasSuffix(t.filename, ".js") {
w.Header().Add("Content-Type", "application/x-javascript")
}
s := roomSettings{Host: r.Host, Name: name}
t.templ.Execute(w, s)
}
var rooms = map[string]*room{}
func signaling(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
name := params["name"]
room, exist := rooms[name]
if !exist {
log.Println("debug: Create new room", name)
room = newRoom()
go room.run(func() {
log.Println("debug: Delete room", name)
delete(rooms, name)
})
rooms[name] = room
}
room.ServeHTTP(w, r)
}
func main() {
colog.SetDefaultLevel(colog.LDebug)
colog.Register()
var addr = flag.String("addr", ":8080", "The listen port of the application.")
flag.Parse()
router := mux.NewRouter()
router.HandleFunc("/WebRTCHandsOn/{name}", (&templateHandler{filename: "index.html"}).ServeHTTP)
router.HandleFunc("/WebRTCHandsOn/{name}/webrtc.js", (&templateHandler{filename: "webrtc.js"}).ServeHTTP)
router.HandleFunc("/WebRTCHandsOnSig/{name}", signaling)
http.Handle("/", router)
log.Println("info: Starting web server on", *addr)
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}