Files
migo/cmd/main.go
2023-07-18 23:54:46 +02:00

107 lines
2.9 KiB
Go

package main
import (
"context"
"embed"
"github.com/Kugelschieber/migo/db"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"time"
)
var (
//go:embed admin/dist/index.html
index []byte
//go:embed admin/dist/favicon.ico
favicon []byte
//go:embed admin/dist/assets
assets embed.FS
)
func main() {
if err := db.Init(); err != nil {
log.Fatalf("Error initializing database: %v", err)
}
defer db.Close()
dev := os.Getenv("MIGO_DEV") != ""
router := chi.NewRouter()
router.Use(middleware.Recoverer)
router.Use(middleware.Compress(5))
router.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://*", "http://*"},
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions},
AllowedHeaders: []string{"*"},
AllowCredentials: true,
MaxAge: 86400,
}))
router.Handle("/admin", http.RedirectHandler("/admin/", http.StatusFound))
router.Route("/admin/", func(r chi.Router) {
if dev {
r.Handle("/assets/*", http.StripPrefix("/admin/assets/", http.FileServer(http.Dir("cmd/admin/dist/assets"))))
r.Get("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "cmd/admin/dist/favicon.ico")
})
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "cmd/admin/dist/index.html")
})
} else {
fs := http.FileServer(http.FS(assets))
r.Handle("/assets/*", http.StripPrefix("/admin/assets/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = filepath.Join("admin/dist/assets", r.URL.Path)
fs.ServeHTTP(w, r)
})))
r.Get("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/x-icon")
if _, err := w.Write(favicon); err != nil {
w.WriteHeader(http.StatusNotFound)
}
})
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
if _, err := w.Write(index); err != nil {
w.WriteHeader(http.StatusNotFound)
}
})
}
})
router.Get("/", func(w http.ResponseWriter, r *http.Request) {
// TODO
w.Write([]byte("<h1>Hello World!</h1>"))
})
server := &http.Server{
Handler: router,
Addr: os.Getenv("MIGO_HOST"),
WriteTimeout: 30 * time.Second,
ReadTimeout: 30 * time.Second,
}
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
<-sigint
log.Println("Shutting down server")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
if err := server.Shutdown(ctx); err != nil {
log.Printf("Error shutting down server gracefully: %v", err)
}
cancel()
}()
log.Println("Starting server")
if err := server.ListenAndServe(); err != nil {
log.Fatalf("Error starting server: %v", err)
}
}