package main import ( "log" "net/http" "text/template" "github.com/google/uuid" "github.com/gorilla/websocket" "github.com/julienschmidt/httprouter" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } func init() { app.router = httprouter.New() app.router.GET("/", app.Index) app.router.GET("/play/:playlist", app.Play) app.router.GET("/reset", app.Reset) app.router.ServeFiles("/js/*filepath", http.Dir("js")) app.router.ServeFiles("/css/*filepath", http.Dir("css")) app.router.HandlerFunc("GET", "/ws", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("WS connection from %v\n", r.RemoteAddr) conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return } err = handleWS(conn) if err != nil { log.Printf("WS connection closed, %v\n", r.RemoteAddr) } })) go func() { log.Fatal(http.ListenAndServe(":8824", app.router)) }() } type IndexData struct { Playlists []Playlist Ambiance []string } func (app App) Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { playlists, err := app.GetPlaylists() if err != nil { http.Error(w, "Unable to get playlists. "+err.Error(), http.StatusInternalServerError) } amblist, err := GetAmbiance() if err != nil { log.Println(err) return } data := IndexData{playlists, amblist} t := template.Must(template.New("index.tmpl").ParseFiles("tmpl/index.tmpl")) err = t.Execute(w, data) if err != nil { http.Error(w, "Unable to load template. "+err.Error(), http.StatusInternalServerError) } } func (app *App) Play(w http.ResponseWriter, r *http.Request, p httprouter.Params) { plname := p.ByName("playlist") if plname == "reset" { app.events.Emit("stop", nil) return } plid, err := uuid.ParseBytes([]byte(plname)) if err != nil { http.Error(w, "Unable to parse uuid. "+err.Error(), http.StatusInternalServerError) } app.events.Emit("new_playlist", plid) } func (app *App) Add(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { r.ParseForm() } func (app *App) Reset(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { app.events.Emit("stop", nil) }