Basic Vue setup.

This commit is contained in:
2023-07-17 23:09:58 +02:00
parent a30ac3f997
commit b5860b4f64
21 changed files with 4335 additions and 6 deletions

View File

@@ -1,16 +1,28 @@
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"
"time"
)
var (
//go:embed admin
admin embed.FS
//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() {
@@ -19,14 +31,80 @@ func main() {
}
defer db.Close()
dev := os.Getenv("MIGO_DEV") != ""
router := chi.NewRouter()
router.Handle("/admin/*", http.FileServer(http.FS(admin)))
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 {
r.Handle("/assets/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// TODO http.StripPrefix("/admin/assets/",
log.Println(r.URL.Path)
d, err := assets.ReadFile("admin/dist/assets/index-e8823577.css")
if err != nil {
log.Println(err)
}
w.Write(d)
}))
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 := http.ListenAndServe(":8080", router); err != nil {
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)
}
}