forked from mtusi2026/mtusi2026lab2
feat: migrate backend to Golang (Gin + GORM)
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/database"
|
||||
"mtusi2026lab2/internal/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateMessageReq struct {
|
||||
Text string `json:"text" binding:"required"`
|
||||
}
|
||||
|
||||
func CreateMessage(c *gin.Context) {
|
||||
reqID, _ := c.Get("request_id")
|
||||
user, _ := c.Get("user")
|
||||
currentUser := user.(models.User)
|
||||
chatIDStr := c.Param("chat_id")
|
||||
|
||||
chatID, err := uuid.Parse(chatIDStr)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"code": "invalid_request", "message": "Invalid UUID format", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
|
||||
var req CreateMessageReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Text) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"code": "invalid_request", "message": "Text cannot be empty", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
|
||||
var member models.ChatMember
|
||||
if err := database.DB.Where("chat_id = ? AND user_id = ?", chatID, currentUser.ID).First(&member).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"code": "not_found", "message": "Chat not found", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
|
||||
msg := models.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: currentUser.ID,
|
||||
Text: req.Text,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
database.DB.Create(&msg)
|
||||
|
||||
c.JSON(http.StatusCreated, formatMessage(msg))
|
||||
}
|
||||
|
||||
func ListMessages(c *gin.Context) {
|
||||
reqID, _ := c.Get("request_id")
|
||||
user, _ := c.Get("user")
|
||||
currentUser := user.(models.User)
|
||||
chatIDStr := c.Param("chat_id")
|
||||
|
||||
chatID, err := uuid.Parse(chatIDStr)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"code": "invalid_request", "message": "Invalid UUID format", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
|
||||
var member models.ChatMember
|
||||
if err := database.DB.Where("chat_id = ? AND user_id = ?", chatID, currentUser.ID).First(&member).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"code": "not_found", "message": "Chat not found", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
|
||||
// СТРОГАЯ ВАЛИДАЦИЯ LIMIT
|
||||
limit := 50
|
||||
if limitParam := c.Query("limit"); limitParam != "" {
|
||||
parsed, err := strconv.Atoi(limitParam)
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"code": "invalid_request", "message": "Invalid limit parameter", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
|
||||
cursor := c.Query("cursor")
|
||||
query := database.DB.Where("chat_id = ?", chatID)
|
||||
|
||||
if cursor != "" {
|
||||
decoded, err := base64.StdEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"code": "invalid_request", "message": "Invalid cursor", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
parts := strings.SplitN(string(decoded), "|", 2)
|
||||
if len(parts) != 2 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"code": "invalid_request", "message": "Invalid cursor", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if err != nil {
|
||||
createdAt, _ = time.Parse(time.RFC3339, parts[0])
|
||||
}
|
||||
msgID, err := uuid.Parse(parts[1])
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"code": "invalid_request", "message": "Invalid cursor", "request_id": reqID}})
|
||||
return
|
||||
}
|
||||
|
||||
query = query.Where("(created_at > ?) OR (created_at = ? AND id > ?)", createdAt, createdAt, msgID)
|
||||
}
|
||||
|
||||
var messages []models.Message
|
||||
query.Order("created_at ASC, id ASC").Limit(limit + 1).Find(&messages)
|
||||
|
||||
var nextCursor interface{} = nil
|
||||
if len(messages) > limit {
|
||||
lastMsg := messages[limit-1]
|
||||
cursorStr := lastMsg.CreatedAt.Format(time.RFC3339Nano) + "|" + lastMsg.ID.String()
|
||||
nextCursor = base64.StdEncoding.EncodeToString([]byte(cursorStr))
|
||||
messages = messages[:limit]
|
||||
}
|
||||
|
||||
items := make([]gin.H, len(messages))
|
||||
for i, msg := range messages {
|
||||
items[i] = formatMessage(msg)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"items": items, "next_cursor": nextCursor})
|
||||
}
|
||||
|
||||
func formatMessage(m models.Message) gin.H {
|
||||
return gin.H{
|
||||
"id": m.ID.String(),
|
||||
"chat_id": m.ChatID.String(),
|
||||
"sender_id": m.SenderID.String(),
|
||||
"text": m.Text,
|
||||
"created_at": m.CreatedAt.UTC().Format("2006-01-02T15:04:05Z"),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user