server.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package server
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "github.com/felamaslen/gmus-backend/pkg/config"
  7. "github.com/felamaslen/gmus-backend/pkg/logger"
  8. "github.com/felamaslen/gmus-backend/pkg/read"
  9. "github.com/go-redis/redis"
  10. "github.com/gorilla/mux"
  11. "github.com/rs/cors"
  12. )
  13. func StartServer() {
  14. conf := config.GetConfig()
  15. l := logger.CreateLogger(conf.LogLevel)
  16. rdb := redis.NewClient(&redis.Options{Addr: conf.RedisUrl})
  17. defer rdb.Close()
  18. if conf.LibraryWatch {
  19. l.Info("Watching library for changes")
  20. go read.WatchLibraryRecursive(l, conf.LibraryDirectory)
  21. } else {
  22. l.Verbose("Not watching library for changes")
  23. }
  24. router := mux.NewRouter()
  25. healthRoutes(l, router)
  26. initPubsub(l, rdb, router)
  27. router.Path("/stream").Methods("GET").HandlerFunc(routeHandler(l, rdb, streamSong))
  28. router.Path("/artists").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchArtists))
  29. router.Path("/albums").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchAlbums))
  30. router.Path("/songs").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchSongs))
  31. router.Path("/song-info").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchSongInfo))
  32. router.Path("/multi-song-info").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchMultiSongInfo))
  33. router.Path("/next-song").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchNextSong))
  34. router.Path("/prev-song").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchPrevSong))
  35. port := conf.Port
  36. handler := cors.New(cors.Options{
  37. AllowedOrigins: conf.AllowedOrigins,
  38. AllowCredentials: true,
  39. }).Handler(router)
  40. l.Info("Starting server on %s:%d\n", conf.Host, port)
  41. log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", conf.Host, port), handler))
  42. }