forked from mtusi2026/mtusi2026lab2
Перенесена ЛР1
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
//регулярка по контракту
|
||||
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// страница выдачи истории сообщений
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func (u *User) Validate() error {
|
||||
if !usernameRegex.MatchString(u.Username) {
|
||||
return fmt.Errorf("username must match [a-z0-9_]{3,32}")
|
||||
}
|
||||
|
||||
nameRunes := utf8.RuneCountInString(u.DisplayName)
|
||||
if nameRunes < 1 || nameRunes > 100 {
|
||||
return fmt.Errorf("display_name length must be between 1 and 100 code points")
|
||||
}
|
||||
|
||||
if strings.TrimSpace(u.DisplayName) == "" {
|
||||
return fmt.Errorf("display_name cannot be only whitespace")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateChatInput(title string, memberIDs []string, callerID string) error {
|
||||
titleRunes := utf8.RuneCountInString(title)
|
||||
if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" {
|
||||
return fmt.Errorf("invalid chat title")
|
||||
}
|
||||
|
||||
if len(memberIDs) == 0 {
|
||||
return fmt.Errorf("member_ids cannot be empty")
|
||||
}
|
||||
|
||||
hasCaller := false
|
||||
seen := make(map[string]bool)
|
||||
|
||||
for _, id := range memberIDs {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return fmt.Errorf("invalid member uuid: %s", id)
|
||||
}
|
||||
if seen[id] {
|
||||
return fmt.Errorf("duplicate member_id: %s", id)
|
||||
}
|
||||
seen[id] = true
|
||||
|
||||
if id == callerID {
|
||||
hasCaller = true
|
||||
}
|
||||
}
|
||||
|
||||
if !hasCaller {
|
||||
return fmt.Errorf("caller must be in member_ids")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateMessageText(text string) error {
|
||||
textRunes := utf8.RuneCountInString(text)
|
||||
if textRunes < 1 || textRunes > 4000 {
|
||||
return fmt.Errorf("message text length must be between 1 and 4000 code points")
|
||||
}
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return fmt.Errorf("message text cannot be only whitespace")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type CursorData struct {
|
||||
CreatedAt time.Time
|
||||
MessageID string
|
||||
ChatID string
|
||||
}
|
||||
|
||||
// EncodeCursor превращает время, message_id и chat_id в непрозрачную base64 строку
|
||||
func EncodeCursor(createdAt time.Time, messageID, chatID string) string {
|
||||
raw := fmt.Sprintf("%s|%s|%s", createdAt.Format(time.RFC3339Nano), messageID, chatID)
|
||||
return base64.StdEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
// DecodeCursor декодирует строку курсора и проверяет, что он принадлежит именно этому чату
|
||||
func DecodeCursor(cursorStr string, expectedChatID string) (*CursorData, error) {
|
||||
bytes, err := base64.StdEncoding.DecodeString(cursorStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid base64 cursor")
|
||||
}
|
||||
|
||||
parts := strings.Split(string(bytes), "|")
|
||||
if len(parts) != 3 {
|
||||
return nil, fmt.Errorf("malformed cursor")
|
||||
}
|
||||
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid cursor timestamp")
|
||||
}
|
||||
|
||||
chatID := parts[2]
|
||||
//защита из контракта: курсор от другого чата должен давать 400
|
||||
if chatID != expectedChatID {
|
||||
return nil, fmt.Errorf("cursor belongs to another chat")
|
||||
}
|
||||
|
||||
return &CursorData{
|
||||
CreatedAt: t,
|
||||
MessageID: parts[1],
|
||||
ChatID: chatID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// страница со списком чатов пользователя
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = fmt.Errorf("not found")
|
||||
ErrConflict = fmt.Errorf("conflict")
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
usersByID map[string]domain.User //key = user UUID
|
||||
usersByUsername map[string]string //key = username для быстрой проверки уникальности
|
||||
|
||||
chatsByID map[string]domain.Chat //key = chat UUID
|
||||
|
||||
messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
usersByID: make(map[string]domain.User),
|
||||
usersByUsername: make(map[string]string),
|
||||
chatsByID: make(map[string]domain.Chat),
|
||||
messagesByChatID: make(map[string][]domain.Message),
|
||||
}
|
||||
}
|
||||
|
||||
// ---пользователи---
|
||||
|
||||
func (s *MemoryStore) CreateUser(username, displayName string) (domain.User, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// дубликат username -> 409 Conflict
|
||||
if _, exists := s.usersByUsername[username]; exists {
|
||||
return domain.User{}, ErrConflict
|
||||
}
|
||||
|
||||
user := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.usersByID[user.ID] = user
|
||||
s.usersByUsername[user.Username] = user.ID
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetUserByID(id string) (domain.User, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
user, exists := s.usersByID[id]
|
||||
if !exists {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// ---чаты---
|
||||
|
||||
func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
//все участники рил существуют
|
||||
for _, memberID := range memberIDs {
|
||||
if _, exists := s.usersByID[memberID]; !exists {
|
||||
return domain.Chat{}, fmt.Errorf("member not found: %s", memberID)
|
||||
}
|
||||
}
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...), //копирую слайс для изоляции
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.chatsByID[chat.ID] = chat
|
||||
s.messagesByChatID[chat.ID] = make([]domain.Message, 0)
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
|
||||
// Требование безопасности: посторонний получает 404, а не 403
|
||||
isMember := false
|
||||
for _, m := range chat.MemberIDs {
|
||||
if m == callerID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !isMember {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatsForUser(userID string, limit int) ([]domain.Chat, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
var result []domain.Chat
|
||||
for _, chat := range s.chatsByID {
|
||||
for _, m := range chat.MemberIDs {
|
||||
if m == userID {
|
||||
result = append(result, chat)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//по контракту: сортировка по created_at, id по возрастанию
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].CreatedAt.Equal(result[j].CreatedAt) {
|
||||
return result[i].ID < result[j].ID
|
||||
}
|
||||
return result[i].CreatedAt.Before(result[j].CreatedAt)
|
||||
})
|
||||
|
||||
if limit > 0 && len(result) > limit {
|
||||
result = result[:limit]
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ---Сообщения---
|
||||
|
||||
func (s *MemoryStore) CreateMessage(
|
||||
chatID, senderID, text string,
|
||||
) (domain.Message, error) {
|
||||
messageID := uuid.NewString()
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
isMember := false
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == senderID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isMember {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
createdAt := time.Now().UTC()
|
||||
|
||||
messages := s.messagesByChatID[chatID]
|
||||
if len(messages) > 0 {
|
||||
lastCreatedAt := messages[len(messages)-1].CreatedAt
|
||||
|
||||
// Обеспечиваем строго возрастающее время внутри каждого чата.
|
||||
if !createdAt.After(lastCreatedAt) {
|
||||
createdAt = lastCreatedAt.Add(time.Nanosecond)
|
||||
}
|
||||
}
|
||||
|
||||
message := domain.Message{
|
||||
ID: messageID,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
|
||||
s.messagesByChatID[chatID] = append(messages, message)
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetMessages(
|
||||
chatID, callerID string,
|
||||
limit int,
|
||||
cursorStr string,
|
||||
) (domain.MessagePage, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists {
|
||||
return domain.MessagePage{}, ErrNotFound
|
||||
}
|
||||
|
||||
isMember := false
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == callerID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isMember {
|
||||
return domain.MessagePage{}, ErrNotFound
|
||||
}
|
||||
|
||||
var cursorData *domain.CursorData
|
||||
if cursorStr != "" {
|
||||
decodedCursor, err := domain.DecodeCursor(cursorStr, chatID)
|
||||
if err != nil {
|
||||
return domain.MessagePage{},
|
||||
fmt.Errorf("invalid cursor: %w", err)
|
||||
}
|
||||
cursorData = decodedCursor
|
||||
}
|
||||
|
||||
messages := s.messagesByChatID[chatID]
|
||||
|
||||
start := 0
|
||||
|
||||
if cursorData != nil {
|
||||
// Срез уже упорядочен во время записи, поэтому вместо
|
||||
// полного прохода используем бинарный поиск.
|
||||
start = sort.Search(len(messages), func(index int) bool {
|
||||
message := messages[index]
|
||||
|
||||
if message.CreatedAt.After(cursorData.CreatedAt) {
|
||||
return true
|
||||
}
|
||||
|
||||
return message.CreatedAt.Equal(cursorData.CreatedAt) &&
|
||||
message.ID > cursorData.MessageID
|
||||
})
|
||||
}
|
||||
|
||||
page := domain.MessagePage{
|
||||
Items: make([]domain.Message, 0),
|
||||
NextCursor: nil,
|
||||
}
|
||||
|
||||
if start >= len(messages) {
|
||||
return page, nil
|
||||
}
|
||||
|
||||
end := len(messages)
|
||||
if limit > 0 && end-start > limit {
|
||||
end = start + limit
|
||||
}
|
||||
|
||||
// копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез
|
||||
page.Items = make([]domain.Message, end-start)
|
||||
copy(page.Items, messages[start:end])
|
||||
|
||||
if end < len(messages) {
|
||||
lastItem := page.Items[len(page.Items)-1]
|
||||
nextCursor := domain.EncodeCursor(
|
||||
lastItem.CreatedAt,
|
||||
lastItem.ID,
|
||||
chatID,
|
||||
)
|
||||
page.NextCursor = &nextCursor
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
var req CreateChatRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid json: "+err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
//вызывающий есть в списке, нет дубликатов, валидные UUID
|
||||
if err := domain.ValidateChatInput(req.Title, req.MemberIDs, currentUser.ID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.CreateChat(req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
//участник не существует -> 400
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusCreated, chat, reqID)
|
||||
}
|
||||
|
||||
// инфа о чате
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.GetChatByID(chatID, currentUser.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
//посторонний или несуществующий чат -> 404
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||
return
|
||||
}
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusOK, chat, reqID)
|
||||
}
|
||||
|
||||
// список всех чатов текущего пользователя
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
limit := 50
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
if limitStr != "" {
|
||||
val, err := strconv.Atoi(limitStr)
|
||||
if err != nil || val < 1 || val > 100 {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "limit must be an integer between 1 and 100", reqID)
|
||||
return
|
||||
}
|
||||
limit = val
|
||||
}
|
||||
|
||||
chats, err := h.store.GetChatsForUser(currentUser.ID, limit)
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
//если чатов нет, сериализую в пустой массив [], а не null
|
||||
if chats == nil {
|
||||
chats = make([]domain.Chat, 0)
|
||||
}
|
||||
|
||||
page := domain.ChatPage{
|
||||
Items: chats,
|
||||
NextCursor: nil,
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusOK, page, reqID)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/store"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *store.MemoryStore
|
||||
}
|
||||
|
||||
func NewHandler(st *store.MemoryStore) *Handler {
|
||||
return &Handler{store: st}
|
||||
}
|
||||
|
||||
// декодирует тело запроса:
|
||||
// Запрещает неизвестные/лишние поля (DisallowUnknownFields) -> 400
|
||||
// Ловит синтаксические ошибки JSON -> 400
|
||||
// Проверяет, что после валидного JSON нет мусора
|
||||
func decodeJSON(r *http.Request, dst any) error {
|
||||
if r.Body == nil {
|
||||
return errors.New("request body is empty")
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// два JSON подряд или мусор в конце — ошибка
|
||||
var extra json.RawMessage
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return errors.New("extra data after JSON")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// HealthLive проверяет, что процесс сервера запущен
|
||||
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
response.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"}, reqID)
|
||||
}
|
||||
|
||||
// HealthReady проверяет, что сервер готов принимать входящие запросы
|
||||
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
response.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"}, reqID)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// CreateMessage отправляет сообщение в чат
|
||||
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
var req CreateMessageRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid json: "+err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
//не пустой, не только пробелы, до 4000 рун
|
||||
if err := domain.ValidateMessageText(req.Text); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
//автор сообщения строго выводится из сессии (currentUser.ID)
|
||||
msg, err := h.store.CreateMessage(chatID, currentUser.ID, req.Text)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
// чата нет/пользователь не участник -> 404
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||
return
|
||||
}
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusCreated, msg, reqID)
|
||||
}
|
||||
|
||||
// GetMessages возвращает историю сообщений чата с пагинацией по курсору
|
||||
func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
limit := 50
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
if limitStr != "" {
|
||||
val, err := strconv.Atoi(limitStr)
|
||||
// Если передан limit=0 или >100 -> 400 invalid_request
|
||||
if err != nil || val < 1 || val > 100 {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "limit must be an integer between 1 and 100", reqID)
|
||||
return
|
||||
}
|
||||
limit = val
|
||||
}
|
||||
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
|
||||
page, err := h.store.GetMessages(chatID, currentUser.ID, limit, cursor)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||
return
|
||||
}
|
||||
//если курсор кривой или от другого чата -> 400 invalid_request
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
// сообщений нет, [] вместо null
|
||||
if page.Items == nil {
|
||||
page.Items = make([]domain.Message, 0)
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusOK, page, reqID)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
|
||||
// CreateUser создает нового пользователя
|
||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
|
||||
var req CreateUserRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "malformed or invalid JSON: "+err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
userCandidate := domain.User{
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
}
|
||||
|
||||
//правила Unicode, длину и пробелы из domain
|
||||
if err := userCandidate.Validate(); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
createdUser, err := h.store.CreateUser(userCandidate.Username, userCandidate.DisplayName)
|
||||
if err != nil {
|
||||
// юзернейм занят — 409
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict, "username already exists", reqID)
|
||||
return
|
||||
}
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "failed to create user", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusCreated, createdUser, reqID)
|
||||
}
|
||||
|
||||
// GetMe возвращает профиль текущего пользователя
|
||||
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
response.WriteJSON(w, http.StatusOK, currentUser, reqID)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const UserContextKey contextKey = "current_user"
|
||||
|
||||
// RequireAuth проверяет наличие и валидность X-User-Id
|
||||
func RequireAuth(st *store.MemoryStore, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := GetRequestID(r.Context())
|
||||
userID := r.Header.Get("X-User-Id")
|
||||
|
||||
if userID == "" {
|
||||
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "missing X-User-Id header", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
//существует ли чел
|
||||
user, err := st.GetUserByID(userID)
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "user not found", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), UserContextKey, user)
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// чисто чтоб зареганного получить из контекста
|
||||
func GetCurrentUser(ctx context.Context) domain.User {
|
||||
if val, ok := ctx.Value(UserContextKey).(domain.User); ok {
|
||||
return val
|
||||
}
|
||||
return domain.User{}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// responseWriterInterceptor перехватывает статус-код ответа для логов
|
||||
type responseWriterInterceptor struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *responseWriterInterceptor) WriteHeader(code int) {
|
||||
w.statusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Logger(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
interceptor := &responseWriterInterceptor{
|
||||
ResponseWriter: w,
|
||||
statusCode: http.StatusOK, // дефолтный статус если WriteHeader не вызывался
|
||||
}
|
||||
|
||||
next.ServeHTTP(interceptor, r)
|
||||
|
||||
reqID := GetRequestID(r.Context())
|
||||
duration := time.Since(start)
|
||||
|
||||
// метаданные без r.Body
|
||||
log.Printf(
|
||||
"[HTTP] %s %s | status: %d | duration: %v | request_id: %s",
|
||||
r.Method,
|
||||
r.URL.Path,
|
||||
interceptor.statusCode,
|
||||
duration,
|
||||
reqID,
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// Recovery перехватывает панику и возвращает клиенту валидный JSON 500
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
reqID := GetRequestID(r.Context())
|
||||
//из контракта: не раскрывать stack trace и внутренности
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"internal server error",
|
||||
reqID,
|
||||
)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RequestIDKey contextKey = "request_id"
|
||||
|
||||
// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := r.Header.Get("X-Request-Id")
|
||||
if reqID == "" {
|
||||
reqID = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
|
||||
ctx := context.WithValue(r.Context(), RequestIDKey, reqID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// GetRequestID достает ID запроса из контекста
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
if val, ok := ctx.Value(RequestIDKey).(string); ok {
|
||||
return val
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// коды ошибок по контракту
|
||||
const (
|
||||
CodeInvalidRequest = "invalid_request"
|
||||
CodeUnauthorized = "unauthorized"
|
||||
CodeNotFound = "not_found"
|
||||
CodeConflict = "conflict"
|
||||
CodeInternalError = "internal_error"
|
||||
)
|
||||
|
||||
type ErrorPayload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// ErrorResponse — строгое тело ответа при любой ошибке
|
||||
type ErrorResponse struct {
|
||||
Error ErrorPayload `json:"error"`
|
||||
}
|
||||
|
||||
// WriteJSON отправляет любой успешный ответ с правильными заголовками
|
||||
func WriteJSON(w http.ResponseWriter, statusCode int, data any, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
if data != nil {
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteError формирует стандартизированную ошибку с совпадением request_id в теле и заголовке
|
||||
func WriteError(w http.ResponseWriter, statusCode int, code string, message string, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
resp := ErrorResponse{
|
||||
Error: ErrorPayload{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
Reference in New Issue
Block a user