|
|
@@ -6,12 +6,18 @@ import (
|
|
|
|
|
|
"github.com/CesarSSH/api-estudiantes/db"
|
|
|
"github.com/CesarSSH/api-estudiantes/models"
|
|
|
+ "github.com/gorilla/mux"
|
|
|
"gorm.io/gorm"
|
|
|
)
|
|
|
|
|
|
func GetEstudiantesHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
var estudiantes []models.Estudiante
|
|
|
- db.DB.Find(&estudiantes)
|
|
|
+
|
|
|
+ // Cargar los estudiantes junto con la asociación de Categorias
|
|
|
+ db.DB.Preload("Categoria").Find(&estudiantes)
|
|
|
+
|
|
|
+ // Codificar y enviar la respuesta en formato JSON
|
|
|
+ w.Header().Set("Content-Type", "application/json")
|
|
|
json.NewEncoder(w).Encode(&estudiantes)
|
|
|
}
|
|
|
|
|
|
@@ -50,3 +56,37 @@ func PostEstudianteHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
w.WriteHeader(http.StatusCreated) // Código 201
|
|
|
json.NewEncoder(w).Encode(&estudiante) // Devuelve el estudiante creado
|
|
|
}
|
|
|
+
|
|
|
+func DeleteEstudianteHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
+ var estudiante models.Estudiante
|
|
|
+ params := mux.Vars(r)
|
|
|
+ db.DB.First(&estudiante, params["id"])
|
|
|
+ if estudiante.ID == 0 {
|
|
|
+ w.WriteHeader(http.StatusNotFound)
|
|
|
+ w.Write([]byte("Estudiante no encontrado"))
|
|
|
+ return
|
|
|
+ }
|
|
|
+ db.DB.Delete(&estudiante) //Esta funcion me desactivar el usuario
|
|
|
+
|
|
|
+ w.Header().Set("Content-Type", "application/json")
|
|
|
+ w.WriteHeader(http.StatusOK)
|
|
|
+ json.NewEncoder(w).Encode(map[string]string{
|
|
|
+ "message": "Estudiante eliminado exitosamente",
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+func GetEstudianteByIdHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
+ var estudiante models.Estudiante
|
|
|
+ params := mux.Vars(r) // Obtener el parametro "id" de la URL
|
|
|
+
|
|
|
+ // Buscar el estudiante por ID y precargar la asociacion con Categoria
|
|
|
+ if err := db.DB.Preload("Categoria").First(&estudiante, params["id"]).Error; err != nil {
|
|
|
+ // Si no encuentra al estudiante, devolver 404 Not Found
|
|
|
+ w.WriteHeader(http.StatusNotFound)
|
|
|
+ w.Write([]byte("Estudiante no encontrado"))
|
|
|
+ return
|
|
|
+ }
|
|
|
+
|
|
|
+ w.Header().Set("Content-Type", "application/json")
|
|
|
+ json.NewEncoder(w).Encode(&estudiante)
|
|
|
+}
|