feat(crud): handlers HTTP y registro de rutas para recursos CRUD
Anade los 5 handlers CRUD genericos (list, get, create, update, delete) a partir de un CRUDResource y *sql.DB, la factory crud_generate_handlers que compone los 5 en un mapa, y crud_register_routes que registra todas las rutas REST en un http.ServeMux con la sintaxis METHOD /path de Go 1.22+. Caracteristicas: - List con paginacion (page, per_page), orden (sort_by, sort_dir) y filtros exactos (filter_<campo>), validando nombres de columna contra la definicion del recurso para evitar SQL injection. - Create valida required y validaciones (min/max, min_length/max_length, pattern, enum) antes de insertar; mapea UNIQUE violations a 409. - Update hace partial update — solo los campos presentes en el JSON. - Delete hace hard delete o soft delete segun CRUDResource.SoftDelete. - UUIDs generados via github.com/google/uuid; timestamps en RFC3339Nano UTC. Los handlers usan las funciones HTTP del registry (http_json_response, http_error_response, http_parse_body) y se pueden componer con el mux via http_router.
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package infra
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// CRUDGetHandler retorna un http.HandlerFunc que busca un registro por id y lo devuelve
|
||||
// como JSON. Usa r.PathValue("id"). Responde 404 si no existe o si esta soft-deleted.
|
||||
func CRUDGetHandler(res CRUDResource, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
HTTPErrorResponse(w, HTTPError{Status: http.StatusBadRequest, Code: "missing_id", Message: "id path parameter is required"})
|
||||
return
|
||||
}
|
||||
|
||||
query := fmt.Sprintf("SELECT * FROM %s WHERE id = ?", res.Table)
|
||||
if res.SoftDelete {
|
||||
query += " AND deleted_at IS NULL"
|
||||
}
|
||||
rows, err := db.Query(query, id)
|
||||
if err != nil {
|
||||
HTTPErrorResponse(w, HTTPError{Status: http.StatusInternalServerError, Code: "db_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
cols, err := rows.Columns()
|
||||
if err != nil {
|
||||
HTTPErrorResponse(w, HTTPError{Status: http.StatusInternalServerError, Code: "db_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if !rows.Next() {
|
||||
HTTPErrorResponse(w, HTTPError{Status: http.StatusNotFound, Code: "not_found", Message: fmt.Sprintf("%s %q not found", res.Name, id)})
|
||||
return
|
||||
}
|
||||
row, err := crudScanRow(rows, cols)
|
||||
if err != nil {
|
||||
HTTPErrorResponse(w, HTTPError{Status: http.StatusInternalServerError, Code: "db_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
HTTPJSONResponse(w, http.StatusOK, row)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user