Files
glancr/cmd/server/main.go

47 lines
878 B
Go

package main
import (
"log"
"net/http"
"os"
"path"
"strings"
"github.com/smjklake/glancr/internal/api"
"github.com/smjklake/glancr/internal/fs"
)
func spaHandler() http.HandlerFunc {
fs := fs.GetUIAssets()
fileServer := http.FileServer(http.FS(fs))
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
fileServer.ServeHTTP(w, r)
return
}
f, err := fs.Open(strings.TrimPrefix(path.Clean(r.URL.Path), "/"))
if err == nil {
defer f.Close()
}
if os.IsNotExist(err) {
r.URL.Path = "/"
}
fileServer.ServeHTTP(w, r)
}
}
func main() {
// Initialize API
apiHandler := api.NewAPI()
// API routes
http.HandleFunc("/api/file", apiHandler.HandleFile)
// SPA handler for everything else
http.HandleFunc("/", spaHandler())
log.Println("Starting glancr on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}