package server import ( "io/fs" "log" "net/http" "os" "text/template" svgtemplater "tomatentum.net/svg-templater" "tomatentum.net/svg-templater/internal/routes" "tomatentum.net/svg-templater/pkg/auth" "tomatentum.net/svg-templater/pkg/svg" ) var mux http.ServeMux func PrepareHTTP() { mux = *http.NewServeMux() registerAuthorizedFunc("/svg/", func(w http.ResponseWriter, r *http.Request) { switch r.Method { case "POST": routes.CreateSVG(w, r) return case "GET": routes.Get(w, r) return } http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) }) registerAuthorizedFunc("/svg/{id}", func(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET", "POST": routes.DownloadSVG(w, r) return case "PATCH": routes.RenameSvg(w, r) return case "DELETE": routes.DeleteSvg(w, r) return } http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) }) registerAuthorizedFunc("/svg/{id}/page/", func(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } routes.AddPage(w, r) }) registerAuthorizedFunc("/svg/{id}/page/{page}", func(w http.ResponseWriter, r *http.Request) { if r.Method != "DELETE" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } routes.DeletePage(w, r) }) registerAuthorizedFunc("/font/", func(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": routes.GetFonts(w, r) case "POST": routes.AddFont(w, r) } }) mux.Handle("/public/", http.StripPrefix("/public/", http.FileServer(svg.Storage.GetPublicDir()))) } func PrepareFrontend(key string) { webFS, _ := fs.Sub(svgtemplater.Frontend, "frontend") mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/app.js" { http.FileServer(http.FS(webFS)).ServeHTTP(w, r) return } tmplData, err := fs.ReadFile(webFS, "app.js") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl, err := template.New("index").Delims("[[", "]]").Parse(string(tmplData)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Execute with environment variables data := map[string]string{ "APIKey": os.Getenv("API_KEY"), "APIUrl": "", } if err := tmpl.Execute(w, data); err != nil { http.Error(w, "Coudln't render template", http.StatusInternalServerError) return } }) } func Start() { log.Println("Starting http server on :3000") handler := corsMiddleware(&mux) if err := http.ListenAndServe(":3000", handler); err != nil { panic(err) } } func registerAuthorized(path string, handler http.Handler) { mux.HandleFunc(path, auth.AuthMiddleware(handler)) log.Println("Registered authorized handler for", path) } func registerAuthorizedFunc(path string, f func(w http.ResponseWriter, r *http.Request)) { registerAuthorized(path, http.HandlerFunc(f)) }