server.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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/go-redis/redis"
  9. "github.com/gorilla/mux"
  10. "github.com/rs/cors"
  11. )
  12. func (s *Server) Init() {
  13. s.l = logger.CreateLogger(config.GetConfig().LogLevel)
  14. s.router = mux.NewRouter()
  15. healthRoutes(s.l, s.router)
  16. }
  17. func (s *Server) Listen() {
  18. conf := config.GetConfig()
  19. handler := cors.New(cors.Options{
  20. AllowedOrigins: conf.AllowedOrigins,
  21. AllowCredentials: true,
  22. }).Handler(s.router)
  23. s.l.Info("Starting server on %s:%d\n", conf.Host, conf.Port)
  24. log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", conf.Host, conf.Port), handler))
  25. }
  26. func StartServer() {
  27. conf := config.GetConfig()
  28. l := logger.CreateLogger(conf.LogLevel)
  29. server := Server{}
  30. server.Init()
  31. rdb := redis.NewClient(&redis.Options{Addr: conf.RedisUrl})
  32. defer rdb.Close()
  33. initPubsub(l, rdb, server.router)
  34. server.router.Path("/stream").Methods("GET").HandlerFunc(routeHandler(l, rdb, streamSong))
  35. server.router.Path("/artists").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchArtists))
  36. server.router.Path("/albums").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchAlbums))
  37. server.router.Path("/songs").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchSongs))
  38. server.router.Path("/song-info").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchSongInfo))
  39. server.router.Path("/multi-song-info").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchMultiSongInfo))
  40. server.router.Path("/next-song").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchNextSong))
  41. server.router.Path("/prev-song").Methods("GET").HandlerFunc(routeHandler(l, rdb, routeFetchPrevSong))
  42. server.Listen()
  43. }