package handlers import ( "fmt" "net/http" "strconv" "strings" "pdf-form-converter/db" ) type FormHandler struct { db *db.DB } func NewFormHandler(d *db.DB) *FormHandler { return &FormHandler{db: d} } func (h *FormHandler) Register(mux *http.ServeMux) { mux.HandleFunc("/form/", h.handleForm) } func (h *FormHandler) handleForm(w http.ResponseWriter, r *http.Request) { path := strings.TrimPrefix(r.URL.Path, "/form/") if path == "" { http.ServeFile(w, r, "static/public/index.html") return } parts := strings.SplitN(path, "/", 2) id, err := strconv.ParseInt(parts[0], 10, 64) if err != nil { http.ServeFile(w, r, "static/public/index.html") return } if len(parts) == 2 && parts[1] == "pdf" && r.Method == http.MethodGet { h.servePDF(w, r, id) return } if len(parts) == 1 && r.Method == http.MethodGet { h.serveFormJSON(w, r, id) return } http.NotFound(w, r) } func (h *FormHandler) serveFormJSON(w http.ResponseWriter, r *http.Request, id int64) { form, err := h.db.GetForm(id) if err != nil { jsonError(w, "form not found", http.StatusNotFound) return } jsonResponse(w, form) } func (h *FormHandler) servePDF(w http.ResponseWriter, r *http.Request, id int64) { form, err := h.db.GetForm(id) if err != nil { jsonError(w, "form not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/pdf") w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"", form.PDFName)) w.Write(form.PDFData) }