소스 검색

Funcion eliminar y traer est por id

cesarssh.dev@gmail.com 1 년 전
부모
커밋
9f55653204
2개의 변경된 파일43개의 추가작업 그리고 1개의 파일을 삭제
  1. 2 0
      main.go
  2. 41 1
      routes/estudiante.route.go

+ 2 - 0
main.go

@@ -26,6 +26,8 @@ func main() {
 	//Estudiantes
 	router.HandleFunc("/api/v1/estudiantes", routes.GetEstudiantesHandler).Methods("GET")
 	router.HandleFunc("/api/v1/estudiante", routes.PostEstudianteHandler).Methods("POST")
+	router.HandleFunc("/api/v1/estudiante/{id}", routes.DeleteEstudianteHandler).Methods("DELETE")
+	router.HandleFunc("/api/v1/estudiante/{id}", routes.GetEstudianteByIdHandler).Methods("GET")
 
 	//Categorias
 	router.HandleFunc("/api/v1/categorias", routes.GetCategoriasHandler).Methods("GET")

+ 41 - 1
routes/estudiante.route.go

@@ -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)
+}