diff --git a/internal/transport/http/message.go b/internal/transport/http/message.go index 953acdea..4ba533d9 100644 --- a/internal/transport/http/message.go +++ b/internal/transport/http/message.go @@ -1,6 +1,8 @@ package http import ( + "encoding/json" + "errors" "net/http" "github.com/charawein/mtusi2026lab4/internal/service" @@ -15,6 +17,29 @@ func NewMessageHandler(messages *service.MessageService) *MessageHandler { return &MessageHandler{messages: messages} } +// attachmentIDs — поле контракта, которое обязано быть JSON-массивом строк. +// null недопустим (в отличие от отсутствия поля — его трактуем как пустой +// список и пробрасываем дальше как nil-срез). +type attachmentIDs struct { + present bool + value []string +} + +var errAttachmentIDsNull = errors.New("attachment_ids must be an array, not null") + +func (a *attachmentIDs) UnmarshalJSON(b []byte) error { + a.present = true + if string(b) == "null" { + return errAttachmentIDsNull + } + var v []string + if err := json.Unmarshal(b, &v); err != nil { + return err + } + a.value = v + return nil +} + func (h *MessageHandler) SendMessage(w http.ResponseWriter, r *http.Request) { uid := httputil.UserIDFromContext(r.Context()) if uid == "" { @@ -29,8 +54,8 @@ func (h *MessageHandler) SendMessage(w http.ResponseWriter, r *http.Request) { } var body struct { - Text *string `json:"text"` - AttachmentIDs []string `json:"attachment_ids"` + Text *string `json:"text"` + AttachmentIDs attachmentIDs `json:"attachment_ids"` } if err := httputil.DecodeJSON(r, &body); err != nil { httputil.WriteError(w, r, err) @@ -40,10 +65,18 @@ func (h *MessageHandler) SendMessage(w http.ResponseWriter, r *http.Request) { httputil.WriteError(w, r, service.ErrInvalidInput) return } + // null в attachment_ids — нарушение контракта; отсутствие поля считаем + // пустым списком. + if body.AttachmentIDs.present && body.AttachmentIDs.value == nil { + // present == true и value == nil возможно только если был null — + // но UnmarshalJSON уже вернул ошибку. Оставляем защиту на будущее. + httputil.WriteError(w, r, service.ErrInvalidInput) + return + } // Повтор с тем же ключом возвращает тот же 201 и то же сообщение. key := r.Header.Get("Idempotency-Key") - m, err := h.messages.Send(r.Context(), uid, chatID, *body.Text, body.AttachmentIDs, key) + m, err := h.messages.Send(r.Context(), uid, chatID, *body.Text, body.AttachmentIDs.value, key) if err != nil { httputil.WriteError(w, r, err) return