arimelody.me/main.go
2024-08-31 01:52:33 +01:00

83 lines
2.2 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"arimelody.me/arimelody.me/api/v1/admin"
"arimelody.me/arimelody.me/api/v1/music"
"arimelody.me/arimelody.me/db"
"arimelody.me/arimelody.me/global"
)
const DEFAULT_PORT int = 8080
func main() {
db := db.InitDatabase()
defer db.Close()
var err error
music.Artists, err = music.PullAllArtists(db)
if err != nil {
fmt.Printf("Failed to pull artists from database: %v\n", err);
panic(1)
}
fmt.Printf("%d artists loaded successfully.\n", len(music.Artists))
music.Releases, err = music.PullAllReleases(db)
if err != nil {
fmt.Printf("Failed to pull releases from database: %v\n", err);
panic(1)
}
fmt.Printf("%d releases loaded successfully.\n", len(music.Releases))
mux := createServeMux()
port := DEFAULT_PORT
fmt.Printf("now serving at http://127.0.0.1:%d\n", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), mux))
}
func createServeMux() *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("/api/v1/admin/", global.HTTPLog(http.StripPrefix("/api/v1/admin", admin.Handler())))
mux.Handle("/music/", global.HTTPLog(http.StripPrefix("/music", music.ServeGateway())))
mux.Handle("/music", global.HTTPLog(music.ServeCatalog()))
mux.Handle("/", global.HTTPLog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" || r.URL.Path == "/index.html" {
global.ServeTemplate("index.html", nil).ServeHTTP(w, r)
return
}
staticHandler().ServeHTTP(w, r)
})))
return mux
}
func staticHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
info, err := os.Stat(filepath.Join("public", filepath.Clean(r.URL.Path)))
// does the file exist?
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
}
// is thjs a directory? (forbidden)
if info.IsDir() {
http.NotFound(w, r)
return
}
http.FileServer(http.Dir("./public")).ServeHTTP(w, r)
})
}