package server import ( "bytes" "fmt" "log/slog" "net/http" "git.lastassault.de/speatzle/morffix/constants" "github.com/jackc/pgx/v5" ) type LibrariesData struct { Libraries []Library } type Library struct { ID string `db:"id"` Name string `db:"name"` Path string `db:"path"` Enable bool `db:"enable"` } func handleLibraries(w http.ResponseWriter, r *http.Request) { data := LibrariesData{} if r.Method == "POST" { err := createLibrary(r) if err != nil { slog.ErrorContext(r.Context(), "Create Library", "err", err) http.Error(w, "Error Create Library: "+err.Error(), http.StatusInternalServerError) return } } rows, err := db.Query(r.Context(), "SELECT id, name, path, enable FROM libraries") if err != nil { slog.ErrorContext(r.Context(), "Query Libraries", "err", err) http.Error(w, "Error Query Libraries: "+err.Error(), http.StatusInternalServerError) return } libraries, err := pgx.CollectRows[Library](rows, pgx.RowToStructByName[Library]) if err != nil { slog.ErrorContext(r.Context(), "Collect Rows", "err", err) http.Error(w, "Error Query Libraries: "+err.Error(), http.StatusInternalServerError) return } data.Libraries = libraries buf := bytes.Buffer{} err = templates.ExecuteTemplate(&buf, constants.LIBRARIES_TEMPLATE_NAME, data) if err != nil { slog.ErrorContext(r.Context(), "Executing Libraries Template", "err", err) http.Error(w, "Error Executing Template: "+err.Error(), http.StatusInternalServerError) return } _, err = w.Write(buf.Bytes()) if err != nil { slog.ErrorContext(r.Context(), "Writing http Response", "err", err) } } func createLibrary(r *http.Request) error { err := r.ParseForm() if err != nil { return fmt.Errorf("Parseing Form: %w", err) } name := r.FormValue("name") path := r.FormValue("path") enable := r.FormValue("enable") == "on" slog.Info("Got Library Create", "name", name, "path", path, "enable", enable) _, err = db.Exec(r.Context(), "INSERT INTO Libraries (name, path, enable) VALUES ($1,$2,$3)", name, path, enable) if err != nil { return fmt.Errorf("Inserting Library: %w", err) } return nil }