refactor bug report handlers to use centralized JSON response functions and add delete functionality

This commit is contained in:
Flavio Fois
2026-03-18 09:32:01 +01:00
parent 52947965db
commit 3f54e1cea4
3 changed files with 102 additions and 121 deletions

View File

@@ -31,9 +31,7 @@ var fileRoles = []struct {
func CreateBugReport(db *sqlx.DB) http.HandlerFunc { func CreateBugReport(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(32 << 20); err != nil { if err := r.ParseMultipartForm(32 << 20); err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "invalid multipart form: "+err.Error())
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "invalid multipart form: " + err.Error()})
return return
} }
@@ -46,9 +44,7 @@ func CreateBugReport(db *sqlx.DB) http.HandlerFunc {
systemInfoStr := r.FormValue("system_info") systemInfoStr := r.FormValue("system_info")
if name == "" || email == "" || description == "" { if name == "" || email == "" || description == "" {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "name, email and description are required")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "name, email and description are required"})
return return
} }
@@ -72,33 +68,26 @@ func CreateBugReport(db *sqlx.DB) http.HandlerFunc {
name, email, description, hwid, hostname, osUser, submitterIP, systemInfo, models.BugReportStatusNew, name, email, description, hwid, hostname, osUser, submitterIP, systemInfo, models.BugReportStatusNew,
) )
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
reportID, err := result.LastInsertId() reportID, err := result.LastInsertId()
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
for _, fr := range fileRoles { for _, fr := range fileRoles {
file, header, err := r.FormFile(fr.field) file, header, err := r.FormFile(fr.field)
if err != nil { if err != nil {
// no file uploaded for this role — skip
continue continue
} }
defer file.Close() defer file.Close()
data, err := io.ReadAll(file) data, err := io.ReadAll(file)
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, "reading file "+fr.field+": "+err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "reading file " + fr.field + ": " + err.Error()})
return return
} }
@@ -118,18 +107,14 @@ func CreateBugReport(db *sqlx.DB) http.HandlerFunc {
reportID, fr.role, filename, mimeType, len(data), data, reportID, fr.role, filename, mimeType, len(data), data,
) )
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
} }
log.Printf("[BUGREPORT] Created successfully with id=%d", reportID) log.Printf("[BUGREPORT] Created successfully with id=%d", reportID)
w.Header().Set("Content-Type", "application/json") jsonCreated(w, map[string]interface{}{
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"success": true, "success": true,
"report_id": reportID, "report_id": reportID,
"message": "Bug report submitted successfully", "message": "Bug report submitted successfully",
@@ -141,14 +126,11 @@ func GetAllBugReports(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var reports []models.BugReport var reports []models.BugReport
if err := db.SelectContext(r.Context(), &reports, "SELECT * FROM emly_bugreports_dev.bug_reports"); err != nil { if err := db.SelectContext(r.Context(), &reports, "SELECT * FROM emly_bugreports_dev.bug_reports"); err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
w.Header().Set("Content-Type", "application/json") jsonOK(w, reports)
_ = json.NewEncoder(w).Encode(reports)
} }
} }
@@ -156,29 +138,22 @@ func GetBugReportByID(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id") id := chi.URLParam(r, "id")
if id == "" { if id == "" {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "missing id parameter")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "missing id parameter"})
return return
} }
var report models.BugReport var report models.BugReport
err := db.GetContext(r.Context(), &report, "SELECT * FROM emly_bugreports_dev.bug_reports WHERE id = ?", id) err := db.GetContext(r.Context(), &report, "SELECT * FROM emly_bugreports_dev.bug_reports WHERE id = ?", id)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusNotFound, "bug report not found")
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "bug report not found"})
return return
} }
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
w.Header().Set("Content-Type", "application/json") jsonOK(w, report)
_ = json.NewEncoder(w).Encode(report)
} }
} }
@@ -186,14 +161,11 @@ func GetReportsCount(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var count int var count int
if err := db.GetContext(r.Context(), &count, "SELECT COUNT(*) FROM emly_bugreports_dev.bug_reports"); err != nil { if err := db.GetContext(r.Context(), &count, "SELECT COUNT(*) FROM emly_bugreports_dev.bug_reports"); err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
w.Header().Set("Content-Type", "application/json") jsonOK(w, map[string]int{"count": count})
_ = json.NewEncoder(w).Encode(map[string]int{"count": count})
} }
} }
@@ -201,22 +173,17 @@ func GetReportFilesByReportID(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id") id := chi.URLParam(r, "id")
if id == "" { if id == "" {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "missing id parameter")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "missing id parameter"})
return return
} }
var files []models.BugReportFile var files []models.BugReportFile
if err := db.SelectContext(r.Context(), &files, "SELECT * FROM emly_bugreports_dev.bug_report_files WHERE report_id = ?", id); err != nil { if err := db.SelectContext(r.Context(), &files, "SELECT * FROM emly_bugreports_dev.bug_report_files WHERE report_id = ?", id); err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
w.Header().Set("Content-Type", "application/json") jsonOK(w, files)
_ = json.NewEncoder(w).Encode(files)
} }
} }
@@ -224,32 +191,24 @@ func GetBugReportZipById(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id") id := chi.URLParam(r, "id")
if id == "" { if id == "" {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "missing id parameter")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "missing id parameter"})
return return
} }
var report models.BugReport var report models.BugReport
err := db.GetContext(r.Context(), &report, "SELECT * FROM emly_bugreports_dev.bug_reports WHERE id = ?", id) err := db.GetContext(r.Context(), &report, "SELECT * FROM emly_bugreports_dev.bug_reports WHERE id = ?", id)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusNotFound, "bug report not found")
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "bug report not found"})
return return
} }
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
var files []models.BugReportFile var files []models.BugReportFile
if err := db.SelectContext(r.Context(), &files, "SELECT * FROM emly_bugreports_dev.bug_report_files WHERE report_id = ?", id); err != nil { if err := db.SelectContext(r.Context(), &files, "SELECT * FROM emly_bugreports_dev.bug_report_files WHERE report_id = ?", id); err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
@@ -279,38 +238,28 @@ func GetBugReportZipById(db *sqlx.DB) http.HandlerFunc {
rf, err := zw.Create("report.txt") rf, err := zw.Create("report.txt")
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
if _, err = rf.Write([]byte(reportText)); err != nil { if _, err = rf.Write([]byte(reportText)); err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
for _, file := range files { for _, file := range files {
ff, err := zw.Create(fmt.Sprintf("%s/%s", file.FileRole, file.Filename)) ff, err := zw.Create(fmt.Sprintf("%s/%s", file.FileRole, file.Filename))
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
if _, err = ff.Write(file.Data); err != nil { if _, err = ff.Write(file.Data); err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
} }
if err := zw.Close(); err != nil { if err := zw.Close(); err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
@@ -324,30 +273,23 @@ func GetReportFileByFileID(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
reportId := chi.URLParam(r, "id") reportId := chi.URLParam(r, "id")
if reportId == "" { if reportId == "" {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "missing report id parameter")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "missing report id parameter"})
return return
} }
fileId := chi.URLParam(r, "file_id") fileId := chi.URLParam(r, "file_id")
if fileId == "" { if fileId == "" {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "missing file id parameter")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "missing file id parameter"})
return return
} }
var file models.BugReportFile var file models.BugReportFile
err := db.GetContext(r.Context(), &file, "SELECT filename, mime_type, data FROM emly_bugreports_dev.bug_report_files WHERE report_id = ? AND id = ?", reportId, fileId) err := db.GetContext(r.Context(), &file, "SELECT filename, mime_type, data FROM emly_bugreports_dev.bug_report_files WHERE report_id = ? AND id = ?", reportId, fileId)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusNotFound, "file not found")
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "file not found"})
return return
} }
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
@@ -368,65 +310,77 @@ func GetReportStatusByID(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
reportId := chi.URLParam(r, "id") reportId := chi.URLParam(r, "id")
if reportId == "" { if reportId == "" {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "missing report id parameter")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "missing report id parameter"})
return
}
var reportStatus models.BugReportStatus
if err := db.GetContext(r.Context(), &reportStatus, "SELECT status FROM emly_bugreports_dev.bug_reports WHERE id = ?", reportId); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
w.Header().Set("Content-Type", "application/json") var reportStatus models.BugReportStatus
_ = json.NewEncoder(w).Encode(map[string]string{"status": string(reportStatus)}) if err := db.GetContext(r.Context(), &reportStatus, "SELECT status FROM emly_bugreports_dev.bug_reports WHERE id = ?", reportId); err != nil {
jsonError(w, http.StatusInternalServerError, err.Error())
return
}
jsonOK(w, map[string]string{"status": string(reportStatus)})
} }
} }
func PatchReportStatus(db *sqlx.DB) http.HandlerFunc { func PatchBugReportStatus(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
reportId := chi.URLParam(r, "id") reportId := chi.URLParam(r, "id")
if reportId == "" { if reportId == "" {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "missing report id parameter")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "missing report id parameter"})
return return
} }
body, err := io.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusBadRequest, "unable to read request body: "+err.Error())
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "unable to read request body: " + err.Error()})
return return
} }
reportStatus := models.BugReportStatus(body) reportStatus := models.BugReportStatus(body)
result, err := db.ExecContext(r.Context(), "UPDATE emly_bugreports_dev.bug_reports SET status = ? WHERE id = ?", reportStatus, reportId) result, err := db.ExecContext(r.Context(), "UPDATE emly_bugreports_dev.bug_reports SET status = ? WHERE id = ?", reportStatus, reportId)
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
rowsAffected, err := result.RowsAffected() rowsAffected, err := result.RowsAffected()
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusInternalServerError, err.Error())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return return
} }
if rowsAffected == 0 { if rowsAffected == 0 {
w.Header().Set("Content-Type", "application/json") jsonError(w, http.StatusNotFound, "bug report not found")
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "bug report not found"})
return return
} }
w.Header().Set("Content-Type", "application/json") jsonOK(w, map[string]string{"message": "status updated successfully"})
_ = json.NewEncoder(w).Encode(map[string]string{"message": "status updated successfully"}) }
}
func DeleteBugReportByID(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
reportId := chi.URLParam(r, "id")
if reportId == "" {
jsonError(w, http.StatusBadRequest, "missing report id parameter")
return
}
result, err := db.ExecContext(r.Context(), "DELETE FROM emly_bugreports_dev.bug_reports WHERE id = ?", reportId)
if err != nil {
jsonError(w, http.StatusInternalServerError, err.Error())
return
}
rowsAffected, err := result.RowsAffected()
if err != nil {
jsonError(w, http.StatusInternalServerError, err.Error())
return
}
if rowsAffected == 0 {
jsonError(w, http.StatusNotFound, "bug report not found")
return
}
jsonOK(w, map[string]string{"message": "bug report deleted successfully"})
} }
} }

View File

@@ -0,0 +1,26 @@
package handlers
import (
"encoding/json"
"net/http"
)
// jsonError writes a JSON error response with the given status code and message.
func jsonError(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": msg})
}
// jsonOK writes a 200 JSON response with the given payload.
func jsonOK(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}
// jsonCreated writes a 201 JSON response with the given payload.
func jsonCreated(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(v)
}

View File

@@ -90,7 +90,8 @@ func main() {
r.Get("/{id}/files", handlers.GetReportFilesByReportID(db)) r.Get("/{id}/files", handlers.GetReportFilesByReportID(db))
r.Get("/{id}/files/{file_id}", handlers.GetReportFileByFileID(db)) r.Get("/{id}/files/{file_id}", handlers.GetReportFileByFileID(db))
r.Get("/{id}/download", handlers.GetBugReportZipById(db)) r.Get("/{id}/download", handlers.GetBugReportZipById(db))
r.Patch("/{id}/status", handlers.PatchReportStatus(db)) r.Patch("/{id}/status", handlers.PatchBugReportStatus(db))
r.Delete("/{id}", handlers.DeleteBugReportByID(db))
}) })
}) })
}) })