Files
MusicServer/musicserver.go

123 lines
2.7 KiB
Go

package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
"strconv"
"time"
)
func main() {
// Get the value of an Environment Variable
host := os.Getenv("DB_HOST")
dbPort, dbPortErr := strconv.Atoi(os.Getenv("DB_PORT"))
if dbPortErr != nil {
dbPort = 0
}
username := os.Getenv("DB_USERNAME")
password := os.Getenv("DB_PASSWORD")
dbName := os.Getenv("DB_NAME")
fmt.Printf("host: %s, dbPort: %v, username: %s, password: %s, dbName: %s\n",
host, dbPort, username, password, dbName)
if host == "" {
host = "localhost"
}
if dbPort == 0 {
dbPort = 5432
}
if username == "" {
username = "sebastian"
}
if password == "" {
password = "950100"
}
if dbName == "" {
dbName = "music_dev_local"
}
initDB(host, dbPort, username, password, dbName)
defer closeDb()
r := mux.NewRouter()
r.HandleFunc("/sync", syncHandler)
r.HandleFunc("/sync/{func}", syncHandler)
r.HandleFunc("/music", musicHandler)
r.HandleFunc("/music/{func}", musicHandler)
r.HandleFunc("/music/{func}/{func2}", musicHandler)
r.HandleFunc("/{func}", indexHandler)
http.Handle("/", r)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
log.Printf("Listening on port %s", port)
log.Printf("Open http://localhost:%s in the browser", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
type VersionData struct {
Version string `json:"version"`
Changelog string `json:"changelog"`
History []VersionData `json:"history"`
}
type SongInfo struct {
Game string `json:"Game"`
GamePlayed int `json:"GamePlayed"`
Song string `json:"Song"`
SongPlayed int `json:"SongPlayed"`
CurrentlyPlaying bool `json:"CurrentlyPlaying"`
SongNo int `json:"SongNo"`
}
type GameData struct {
id int
gameName string
added time.Time
deleted time.Time
lastChanged time.Time
path string
timesPlayed int
lastPlayed time.Time
numberOfSongs int32
}
type SongData struct {
gameId int
songName string
path string
timesPlayed int
}
func setCorsAndNoCacheHeaders(w *http.ResponseWriter, r *http.Request) {
var etagHeaders = []string{
"ETag",
"If-Modified-Since",
"If-Match",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
}
(*w).Header().Set("Expires", "Tue, 03 Jul 2001 06:00:00 GMT")
(*w).Header().Set("Last-Modified", time.Now().String()+" GMT")
(*w).Header().Set("Cache-Control", "no-cache, no-store, private, max-age=0")
(*w).Header().Set("Pragma", "no-cache")
(*w).Header().Set("X-Accel-Expires", "0")
(*w).Header().Set("Access-Control-Allow-Origin", "*")
for _, v := range etagHeaders {
if r.Header.Get(v) != "" {
r.Header.Del(v)
}
}
}