forked from mtusi2026/mtusi2026lab2
feat: migrate backend to Golang (Gin + GORM)
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/database"
|
||||
"mtusi2026lab2/internal/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CreateUserReq struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
DisplayName string `json:"display_name" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
func RegisterUser(c *gin.Context) {
|
||||
reqID, _ := c.Get("request_id")
|
||||
var req CreateUserReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"code": "invalid_request", "message": "Invalid request", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
user := models.User{
|
||||
ID: uuid.New(),
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
PasswordHash: string(hashedPassword),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
if err := database.DB.Create(&user).Error; err != nil {
|
||||
if err == gorm.ErrDuplicatedKey || strings.Contains(err.Error(), "duplicate key") {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": gin.H{"code": "conflict", "message": "Username already exists", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": gin.H{"code": "internal_error", "message": "Internal server error", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, formatUser(user))
|
||||
}
|
||||
|
||||
func GetMe(c *gin.Context) {
|
||||
user, _ := c.Get("user")
|
||||
c.JSON(http.StatusOK, formatUser(user.(models.User)))
|
||||
}
|
||||
|
||||
func formatUser(u models.User) gin.H {
|
||||
return gin.H{
|
||||
"id": u.ID.String(),
|
||||
"username": u.Username,
|
||||
"display_name": u.DisplayName,
|
||||
"created_at": u.CreatedAt.UTC().Format("2006-01-02T15:04:05Z"),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user