77 lines
1.8 KiB
Go
Executable File
77 lines
1.8 KiB
Go
Executable File
// internal/handler/user_handler.go
|
|
package handler
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/rovina/zsp-backend/internal/dto"
|
|
"github.com/rovina/zsp-backend/internal/service"
|
|
)
|
|
|
|
type UserHandler struct {
|
|
userService service.UserService
|
|
}
|
|
|
|
func NewUserHandler(userService service.UserService) *UserHandler {
|
|
return &UserHandler{userService: userService}
|
|
}
|
|
|
|
func (h *UserHandler) Register(c *gin.Context) {
|
|
var req dto.CreateUserRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("bind json error: %s", err.Error())})
|
|
return
|
|
}
|
|
user, err := h.userService.Register(&req)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, gin.H{
|
|
"message": "User registered successfully",
|
|
"user": user,
|
|
})
|
|
}
|
|
|
|
func (h *UserHandler) Login(c *gin.Context) {
|
|
var req dto.LoginRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
user, token, err := h.userService.Login(&req)
|
|
fmt.Println(user)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "Login successful",
|
|
"user": user,
|
|
"token": token,
|
|
})
|
|
}
|
|
|
|
func (h *UserHandler) GetUser(c *gin.Context) {
|
|
idStr := c.Param("id")
|
|
id, err := strconv.ParseUint(idStr, 10, 32)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
|
|
return
|
|
}
|
|
|
|
user, err := h.userService.GetUserByID(uint(id))
|
|
if err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"user": user})
|
|
}
|