Files
mtusi2026lab7/src/backend/handlers/http.go
T

164 lines
5.5 KiB
Go

package handlers
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"log"
"net/http"
"strconv"
"time"
"messenger/src/backend/repositories"
"messenger/src/backend/services"
)
type healthResponse struct {
Status string `json:"status"`
}
type apiError struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
type errorResponse struct {
Error apiError `json:"error"`
}
func newRequestID() string {
bytes := make([]byte, 16)
if _, err := rand.Read(bytes); err != nil {
return "request-id-generation-failed"
}
return hex.EncodeToString(bytes)
}
func writeError(w http.ResponseWriter, status int, code, message, requestID string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
response := errorResponse{Error: apiError{Code: code, Message: message, RequestID: requestID}}
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Printf("failed to encode error response: %v", err)
}
}
func writeServiceError(w http.ResponseWriter, err error, requestID string) {
var upload repositories.UploadError
if errors.As(err, &upload) {
writeError(w, upload.Status, upload.Code, upload.Message, requestID)
return
}
var invalid services.InvalidInput
switch {
case errors.As(err, &invalid):
writeError(w, 400, "invalid_request", invalid.Message, requestID)
case errors.Is(err, services.ErrPayloadTooLarge):
writeError(w, 413, "payload_too_large", "image exceeds upload limits", requestID)
case errors.Is(err, services.ErrUnsupportedMedia):
writeError(w, 415, "unsupported_media_type", "a valid PNG or JPEG matching Content-Type is required", requestID)
case errors.Is(err, services.ErrAttachmentNotFound):
writeError(w, 404, "not_found", "attachment not found", requestID)
case errors.Is(err, services.ErrConflict):
writeError(w, 409, "conflict", "request conflicts with an existing resource", requestID)
case errors.Is(err, services.ErrUnknownUser):
writeError(w, 401, "unauthorized", "unknown user", requestID)
case errors.Is(err, services.ErrChatNotFound):
writeError(w, 404, "not_found", "chat not found", requestID)
default:
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
}
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(value); err != nil {
log.Printf("failed to encode response: %v", err)
}
}
func requestUserID(w http.ResponseWriter, r *http.Request, requestID string) (string, bool) {
id := currentUserID(r)
if id == "" {
writeError(w, 401, "unauthorized", "valid Bearer session is required", requestID)
return "", false
}
return id, true
}
func pageParams(w http.ResponseWriter, r *http.Request, requestID string) (int, string, bool) {
limit := 50
if values, exists := r.URL.Query()["limit"]; exists {
if len(values) != 1 || values[0] == "" {
writeError(w, 400, "invalid_request", "invalid limit", requestID)
return 0, "", false
}
parsed, err := strconv.Atoi(values[0])
if err != nil {
writeError(w, 400, "invalid_request", "limit must be between 1 and 100", requestID)
return 0, "", false
}
limit = parsed
}
var cursor string
if values, exists := r.URL.Query()["cursor"]; exists {
if len(values) != 1 || values[0] == "" {
writeError(w, 400, "invalid_request", "invalid cursor", requestID)
return 0, "", false
}
cursor = values[0]
}
return limit, cursor, true
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
requestID := newRequestID()
w.Header().Set("X-Request-Id", requestID)
if r.Method != http.MethodGet {
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
return
}
writeJSON(w, 200, healthResponse{"ok"})
}
func readyHandler(health *services.HealthService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestID := newRequestID()
w.Header().Set("X-Request-Id", requestID)
if r.Method != http.MethodGet {
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
return
}
// Readiness must finish before HAProxy's one-second check read timeout.
ctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)
defer cancel()
if err := health.Ready(ctx); err != nil {
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
return
}
writeJSON(w, 200, healthResponse{"ok"})
}
}
func NewRouter(health *services.HealthService, users *services.UserService, sessions *services.SessionService, chats *services.ChatService, messages *services.MessageService, attachmentServices ...*services.AttachmentService) http.Handler {
var attachments *services.AttachmentService
if len(attachmentServices) > 0 {
attachments = attachmentServices[0]
}
mux := http.NewServeMux()
mux.HandleFunc("/health/live", healthHandler)
mux.HandleFunc("/health/ready", readyHandler(health))
mux.Handle("/api/v1/users", createUserHandler(users))
mux.Handle("/api/v1/auth/sessions", sessionHandler(sessions))
mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions)))
mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(users)))
mux.Handle("/api/v1/chats", authRequired(sessions, chatCollectionHandler(chats)))
mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages, attachments)))
if attachments != nil {
mux.Handle("/api/v1/attachments/", authRequired(sessions, attachmentHandler(attachments)))
}
return withInstance(mux)
}