user_handler.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package handlers
  2. import (
  3. "github.com/CesarSSH/cqrs-api-go/internal/command"
  4. "github.com/CesarSSH/cqrs-api-go/internal/service"
  5. "encoding/json"
  6. "net/http"
  7. )
  8. type UserHandler struct {
  9. commandService *service.UserCommandService
  10. queryService *service.UserQueryService
  11. }
  12. func NewUserHandler(cmdService *service.UserCommandService, qryService *service.UserQueryService) *UserHandler {
  13. return &UserHandler{
  14. commandService: cmdService,
  15. queryService: qryService,
  16. }
  17. }
  18. func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
  19. var cmd command.CreateUserCommand
  20. if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
  21. http.Error(w, err.Error(), http.StatusBadRequest)
  22. return
  23. }
  24. // Llamar a la validación
  25. if err := cmd.Validate(); err != nil {
  26. http.Error(w, err.Error(), http.StatusBadRequest)
  27. return
  28. }
  29. if err := h.commandService.CreateUser(&cmd); err != nil {
  30. http.Error(w, err.Error(), http.StatusInternalServerError)
  31. return
  32. }
  33. w.WriteHeader(http.StatusCreated)
  34. // Enviar un mensaje de éxito como respuesta
  35. response := map[string]string{"message": "Usuario creado"}
  36. json.NewEncoder(w).Encode(response)
  37. }
  38. func (h *UserHandler) GetUsers(w http.ResponseWriter, r *http.Request) {
  39. users, err := h.queryService.GetUsers()
  40. if err != nil {
  41. http.Error(w, err.Error(), http.StatusInternalServerError)
  42. return
  43. }
  44. w.Header().Set("Content-Type", "application/json")
  45. json.NewEncoder(w).Encode(users)
  46. }