на оценку 3

This commit is contained in:
2026-10-21 13:51:35 +03:00
parent 3f69970b05
commit bd28f1ae26
24 changed files with 1130 additions and 91 deletions
@@ -3,6 +3,7 @@ package handlers
import (
"errors"
"net/http"
"regexp"
"strings"
"mtusi2026lab3/internal/application"
@@ -14,15 +15,25 @@ import (
"github.com/google/uuid"
)
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
currentUser := middleware.GetCurrentUser(r.Context())
chatID := r.PathValue("chat_id")
if _, err := uuid.Parse(chatID); err != nil {
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
if err != nil {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"invalid chat_id uuid", requestID)
return
}
chatID := parsedChatID.String()
idempotencyKey := r.Header.Get("Idempotency-Key")
if !idempotencyKeyPattern.MatchString(idempotencyKey) {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"Idempotency-Key must match [A-Za-z0-9._:-]{1,128}", requestID)
return
}
var request dto.CreateMessageRequest
if err := decodeJSON(r, &request); err != nil {
@@ -30,8 +41,18 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
return
}
message, err := h.service.SendMessage(r.Context(), application.SendMessageCommand{
ActorID: currentUser.ID, ChatID: chatID, Text: request.Text,
ActorID: currentUser.ID,
ChatID: chatID,
Text: request.Text,
Method: http.MethodPost,
CanonicalPath: "/api/v1/chats/" + chatID + "/messages",
IdempotencyKey: idempotencyKey,
})
if errors.Is(err, application.ErrIdempotencyConflict) {
response.WriteError(w, http.StatusConflict, response.CodeConflict,
"Idempotency-Key is already used for another request", requestID)
return
}
if errors.Is(err, application.ErrInvalidInput) {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
@@ -0,0 +1,15 @@
package middleware
import "net/http"
const InstanceIDHeader = "X-Instance-Id"
// InstanceID identifies the process that actually produced the response.
// It must wrap recovery and routing so even errors, health checks and 404/405
// responses carry the same stable process identifier.
func InstanceID(instanceID string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(InstanceIDHeader, instanceID)
next.ServeHTTP(w, r)
})
}
@@ -0,0 +1,50 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
handler := InstanceID("api-01", mux)
for _, test := range []struct {
path string
wantStatus int
}{
{path: "/ok", wantStatus: http.StatusNoContent},
{path: "/missing", wantStatus: http.StatusNotFound},
} {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
if recorder.Code != test.wantStatus {
t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus)
}
if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" {
t.Fatalf("%s: got instance ID %q, want api-01", test.path, got)
}
}
}
func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) {
panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
panic("test panic")
})
handler := InstanceID("api-panic", Recovery(panicking))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil))
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("got status %d, want 500", recorder.Code)
}
if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" {
t.Fatalf("got instance ID %q, want api-panic", got)
}
}