/
main.go
80 lines (70 loc) · 1.76 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"
"fmt"
"golang.org/x/net/websocket"
"html/template"
"net/http"
"os"
"time"
)
var (
PORT string
wsocket Websockets
wsCntrl Websockets
waiting_time int
songStartTime time.Time
songLength int
)
func init() {
const (
defaultPort = "8080"
portMessage = "The port of the Tunein Server"
)
flag.StringVar(&PORT, "p", defaultPort, portMessage)
}
type TuneInPage struct {
MusicUrl string
ControlDataUrl string
}
func handler(ws *websocket.Conn) {
wchan := make(chan string)
wsocket.Add(ws, wchan)
msg := <-wchan
fmt.Fprintf(os.Stdout, "Music Go Routine exited: %s\n", msg)
}
func ctrlHandler(ws *websocket.Conn) {
wchan := make(chan string)
wsCntrl.Add(ws, wchan)
waiting_time = calculateTimeDiff()
//fmt.Println("waiting time: ", waiting_time)
cntrlmsg := ControlMsg{Name: "", Duration: waiting_time, Command: "wait"}
websocket.JSON.Send(ws, cntrlmsg)
msg := <-wchan
fmt.Fprintf(os.Stdout, "Ctrl Go Routine exited: %s\n", msg)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
hostname := getLocalIP()
musicUrl := "ws://" + hostname + ":" + PORT + "/radio"
ctrlDataUrl := "ws://" + hostname + ":" + PORT + "/ctrl"
t, err := template.ParseFiles("tmpl/index.tmpl")
if err != nil {
//fmt.Fprintf(os.Stderr, "Unable to load template file: "+err.Error())
return
}
p := TuneInPage{MusicUrl: musicUrl, ControlDataUrl: ctrlDataUrl}
t.Execute(w, p)
}
func main() {
flag.Parse()
wsocket.Init()
wsCntrl.Init()
go playRadio(wsocket, wsCntrl)
http.Handle("/radio", websocket.Handler(handler))
http.Handle("/ctrl", websocket.Handler(ctrlHandler))
http.HandleFunc("/", rootHandler)
err := http.ListenAndServe(":"+PORT, nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}