quintodrome/server/server.go

91 lines
2 KiB
Go
Raw Normal View History

2020-01-13 13:06:47 -09:00
package server
import (
"net/http"
"os"
"path/filepath"
"time"
"github.com/cloudsonic/sonic-server/conf"
2020-01-08 16:45:07 -09:00
"github.com/cloudsonic/sonic-server/log"
2020-01-16 12:53:48 -09:00
"github.com/cloudsonic/sonic-server/scanner"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
2020-01-09 09:51:54 -09:00
"github.com/go-chi/cors"
)
2020-01-13 14:24:42 -09:00
const Version = "0.2"
2020-01-13 13:06:47 -09:00
type Server struct {
Scanner *scanner.Scanner
router *chi.Mux
}
func New(scanner *scanner.Scanner) *Server {
a := &Server{Scanner: scanner}
2020-01-15 13:48:46 -09:00
if !conf.Sonic.DevDisableBanner {
showBanner(Version)
}
2020-01-08 06:25:23 -09:00
initMimeTypes()
a.initRoutes()
a.initScanner()
2020-01-11 09:00:03 -09:00
return a
}
2020-01-13 13:06:47 -09:00
func (a *Server) MountRouter(path string, subRouter http.Handler) {
2020-01-19 15:34:54 -09:00
log.Info("Mounting routes", "path", path)
a.router.Group(func(r chi.Router) {
r.Use(middleware.Logger)
r.Mount(path, subRouter)
})
}
2020-01-13 13:06:47 -09:00
func (a *Server) Run(addr string) {
log.Info("CloudSonic server is accepting requests", "address", addr)
2020-01-08 16:45:07 -09:00
log.Error(http.ListenAndServe(addr, a.router))
}
2020-01-13 13:06:47 -09:00
func (a *Server) initRoutes() {
r := chi.NewRouter()
2020-01-09 09:51:54 -09:00
r.Use(cors.Default().Handler)
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Recoverer)
2020-01-08 20:18:55 -09:00
r.Use(middleware.Compress(5, "application/xml", "application/json", "application/javascript"))
r.Use(middleware.Heartbeat("/ping"))
2020-01-08 16:45:07 -09:00
r.Use(InjectLogger)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
2020-01-19 15:34:54 -09:00
http.Redirect(w, r, "/app", 302)
})
2020-01-19 15:34:54 -09:00
workDir, _ := os.Getwd()
2020-01-08 07:13:05 -09:00
filesDir := filepath.Join(workDir, "Jamstash-master/dist")
2020-01-19 15:34:54 -09:00
FileServer(r, "/Jamstash", "/Jamstash", http.Dir(filesDir))
a.router = r
}
2020-01-16 12:53:48 -09:00
func (a *Server) initScanner() {
go func() {
for {
select {
case <-time.After(5 * time.Second):
err := a.Scanner.RescanAll(false)
if err != nil {
log.Error("Error scanning media folder", "folder", conf.Sonic.MusicFolder, err)
}
}
}
}()
}
2020-01-08 16:45:07 -09:00
func InjectLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = log.NewContext(r.Context(), "requestId", ctx.Value(middleware.RequestIDKey))
next.ServeHTTP(w, r.WithContext(ctx))
})
}