forked from mtusi2026/mtusi2026lab3
Implement lab 3 level 4 failover and idempotency
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
authService *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{authService: authService}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
var probe [1]byte
|
||||
|
||||
n, err := r.Body.Read(probe[:])
|
||||
|
||||
if n > 0 || (err != nil && !errors.Is(err, io.EOF)) {
|
||||
_ = httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
|
||||
Code: "invalid_request",
|
||||
Message: "Request body must be empty",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
createdSession, err := h.authService.CreateSession(r.Context(), username, password)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := createSessionResponse{
|
||||
Token: createdSession.Token,
|
||||
TokenType: createdSession.TokenType,
|
||||
ExpiresAt: httputils.FormatTime(createdSession.ExpiresAt),
|
||||
User: UserResponse{
|
||||
Username: createdSession.User.Username,
|
||||
ID: createdSession.User.ID,
|
||||
DisplayName: createdSession.User.DisplayName,
|
||||
CreatedAt: httputils.FormatTime(createdSession.User.CreatedAt),
|
||||
},
|
||||
}
|
||||
|
||||
httputils.WriteJSON[createSessionResponse](w, http.StatusCreated, response)
|
||||
|
||||
}
|
||||
|
||||
func (h *AuthHandler) DeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
token, ok := httputils.ExtractBearerToken(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
err := h.authService.RevokeSession(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package handler
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type createSessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chatService *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chatService *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chatService: chatService}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
req, code := httputils.Decode[chatCreateRequest](r)
|
||||
|
||||
if code != http.StatusOK {
|
||||
if code == http.StatusUnsupportedMediaType {
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.chatService.Create(r.Context(), req.Title, req.MemberIDs, userID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := chatResponse{
|
||||
Title: result.Title,
|
||||
MemberIDs: result.MemberIDs,
|
||||
ID: result.ID,
|
||||
CreatedAt: httputils.FormatTime(result.CreatedAt),
|
||||
}
|
||||
|
||||
_ = httputils.WriteJSON[chatResponse](w, http.StatusCreated, response)
|
||||
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChatsByUserID(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
limit, cursor, ok := httputils.GetLimitAndCursor(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
chats, nextCursor, err := h.chatService.GetChatsByUserID(r.Context(), userID, limit, cursor)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
chatResponses := make([]chatResponse, len(chats))
|
||||
for index, chat := range chats {
|
||||
chatResponses[index] = *convertChatModelToResponse(chat)
|
||||
}
|
||||
|
||||
response := chatGetByUserIDResponse{
|
||||
Items: chatResponses,
|
||||
NextCursor: nextCursor,
|
||||
}
|
||||
|
||||
_ = httputils.WriteJSON[chatGetByUserIDResponse](w, http.StatusOK, response)
|
||||
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChatByChatID(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
chat, err := h.chatService.GetChatByID(r.Context(), chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertChatModelToResponse(chat)
|
||||
_ = httputils.WriteJSON[chatResponse](w, http.StatusOK, *response)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type chatCreateRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type chatResponse struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
ID string `json:"id"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatGetByUserIDResponse struct {
|
||||
Items []chatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func convertChatModelToResponse(model *model.Chat) *chatResponse {
|
||||
return &chatResponse{
|
||||
Title: model.Title,
|
||||
ID: model.ID,
|
||||
MemberIDs: model.MemberIDs,
|
||||
CreatedAt: httputils.FormatTime(model.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type HealthHandler struct {
|
||||
pool *pgxpool.Pool
|
||||
redisClient *redis.Client
|
||||
}
|
||||
|
||||
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client) *HealthHandler {
|
||||
return &HealthHandler{pool: pool, redisClient: redisClient}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
response := HealthResponse{Status: "ok"}
|
||||
err := httputils.WriteJSON[HealthResponse](w, http.StatusOK, response)
|
||||
if err != nil {
|
||||
slog.Error("failed to write health response", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
if err := h.pool.Ping(ctx); err != nil {
|
||||
slog.Error("database readiness check failed", "error", err)
|
||||
if writeErr := httputils.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
httputils.ErrorDetails{
|
||||
Message: "unavailable",
|
||||
Code: "unavailable",
|
||||
RequestID: requestID,
|
||||
},
|
||||
); writeErr != nil {
|
||||
slog.Error("failed to write readiness response", "error", writeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.redisClient.Ping(ctx).Err(); err != nil {
|
||||
slog.Error("redis readiness check failed", "error", err)
|
||||
if writeErr := httputils.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
httputils.ErrorDetails{
|
||||
Message: "unavailable",
|
||||
Code: "unavailable",
|
||||
RequestID: requestID,
|
||||
},
|
||||
); writeErr != nil {
|
||||
slog.Error("failed to write readiness response", "error", writeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
response := HealthResponse{Status: "ok"}
|
||||
err := httputils.WriteJSON[HealthResponse](w, http.StatusOK, response)
|
||||
if err != nil {
|
||||
slog.Error("failed to write health response", "error", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (h *HealthHandler) NotFoundRoute(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
err := httputils.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
httputils.ErrorDetails{
|
||||
Code: "not_found",
|
||||
Message: "Not Found",
|
||||
RequestID: requestID,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
slog.Error("failed to write not found response", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package handler
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type MessageHandler struct {
|
||||
messageService *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(messageService *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{messageService: messageService}
|
||||
}
|
||||
|
||||
func (h *MessageHandler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
req, code := httputils.Decode[messageCreateRequest](r)
|
||||
|
||||
if code != http.StatusOK {
|
||||
if code == http.StatusUnsupportedMediaType {
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
|
||||
if ok := httputils.CheckIdempotencyKeyPattern(key); !ok {
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
|
||||
Code: "invalid_request",
|
||||
Message: "wrong Idempotency-Key",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := h.messageService.CreateMessage(r.Context(), req.Text, chatID, userID, key)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertMessageModelToResponse(message)
|
||||
|
||||
_ = httputils.WriteJSON[messageResponse](w, http.StatusCreated, *response)
|
||||
|
||||
}
|
||||
|
||||
func (h *MessageHandler) GetMessagesByChatID(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
limit, cursor, ok := httputils.GetLimitAndCursor(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
messages, nextCursor, err := h.messageService.GetMessagesByChatID(r.Context(), chatID, userID, limit, cursor)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
messageResponses := make([]messageResponse, len(messages))
|
||||
for index, message := range messages {
|
||||
messageResponses[index] = *convertMessageModelToResponse(message)
|
||||
}
|
||||
|
||||
response := messageGetResponse{
|
||||
Items: messageResponses,
|
||||
NextCursor: nextCursor,
|
||||
}
|
||||
|
||||
_ = httputils.WriteJSON[messageGetResponse](w, http.StatusOK, response)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type messageCreateRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type messageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type messageGetResponse struct {
|
||||
Items []messageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func convertMessageModelToResponse(message *model.Message) *messageResponse {
|
||||
return &messageResponse{
|
||||
ID: message.ID,
|
||||
ChatID: message.ChatID,
|
||||
SenderID: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: httputils.FormatTime(message.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
userService *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(service *service.UserService) *UserHandler {
|
||||
return &UserHandler{userService: service}
|
||||
}
|
||||
|
||||
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
req, code := httputils.Decode[userCreateRequest](r)
|
||||
|
||||
if code != http.StatusOK {
|
||||
if code == http.StatusUnsupportedMediaType {
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userService.CreateUser(r.Context(), req.Username, req.DisplayName, req.Password)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertUserModelToResponse(user)
|
||||
|
||||
_ = httputils.WriteJSON[userResponse](w, http.StatusCreated, *response)
|
||||
|
||||
}
|
||||
|
||||
func (h *UserHandler) GetCurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
user, err := h.userService.GetUser(r.Context(), userID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertUserModelToResponse(user)
|
||||
|
||||
_ = httputils.WriteJSON[userResponse](w, http.StatusOK, *response)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type userCreateRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func convertUserModelToResponse(user *model.User) *userResponse {
|
||||
return &userResponse{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: httputils.FormatTime(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package httputils
|
||||
|
||||
import (
|
||||
"encoding/json/v2"
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorDetails `json:"error"`
|
||||
}
|
||||
|
||||
type ErrorDetails struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func Decode[T any](r *http.Request) (*T, int) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return nil, http.StatusUnsupportedMediaType
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
|
||||
if !utf8.Valid(body) {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
|
||||
req := new(T)
|
||||
|
||||
err = json.Unmarshal(body, req, json.RejectUnknownMembers(true))
|
||||
if err != nil {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
return req, http.StatusOK
|
||||
|
||||
}
|
||||
|
||||
func GetLimitAndCursor(r *http.Request) (limit *int, cursor *string, ok bool) {
|
||||
query := r.URL.Query()
|
||||
|
||||
var currentLimit *int
|
||||
|
||||
if query.Has("limit") {
|
||||
limitStr := query.Get("limit")
|
||||
|
||||
if limitStr == "" {
|
||||
return nil, nil, false
|
||||
}
|
||||
limitInt, err := strconv.Atoi(limitStr)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
currentLimit = &limitInt
|
||||
|
||||
}
|
||||
|
||||
var currentCursor *string
|
||||
if query.Has("cursor") {
|
||||
cursor := query.Get("cursor")
|
||||
currentCursor = &cursor
|
||||
}
|
||||
|
||||
return currentLimit, currentCursor, true
|
||||
}
|
||||
|
||||
func WriteJSON[T any](w http.ResponseWriter, status int, response T) error {
|
||||
data, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_, err = w.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func ErrorFromService(err error) (int, string) {
|
||||
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvalidInput):
|
||||
return http.StatusBadRequest, "invalid_request"
|
||||
|
||||
case errors.Is(err, service.ErrNotFound):
|
||||
return http.StatusNotFound, "not_found"
|
||||
|
||||
case errors.Is(err, service.ErrAlreadyExists):
|
||||
return http.StatusConflict, "conflict"
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
return http.StatusUnauthorized, "unauthorized"
|
||||
case errors.Is(err, service.ErrServiceUnavailable):
|
||||
return http.StatusServiceUnavailable, "unavailable"
|
||||
case errors.Is(err, service.ErrConflict):
|
||||
return http.StatusConflict, "conflict"
|
||||
default:
|
||||
return http.StatusInternalServerError, "internal_error"
|
||||
}
|
||||
}
|
||||
|
||||
func WriteBasicUnauthorized(w http.ResponseWriter, requestID string) error {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
|
||||
return WriteError(w, http.StatusUnauthorized, ErrorDetails{
|
||||
Code: "unauthorized",
|
||||
Message: "Unauthorized",
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
func WriteBearerUnauthorized(w http.ResponseWriter, requestID string) error {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Bearer realm="messenger"`,
|
||||
)
|
||||
|
||||
return WriteError(w, http.StatusUnauthorized, ErrorDetails{
|
||||
Code: "unauthorized",
|
||||
Message: "Unauthorized",
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, code int, errorDetails ErrorDetails) error {
|
||||
return WriteJSON(w, code, ErrorResponse{Error: errorDetails})
|
||||
|
||||
}
|
||||
func WriteServiceError(w http.ResponseWriter, err error, requestID string) error {
|
||||
status, code := ErrorFromService(err)
|
||||
|
||||
if status >= http.StatusInternalServerError {
|
||||
slog.Error("request failed",
|
||||
"error", err,
|
||||
"request_id", requestID,
|
||||
"status", status,
|
||||
"code", code,
|
||||
)
|
||||
}
|
||||
|
||||
return WriteJSON(w, status, ErrorResponse{
|
||||
Error: ErrorDetails{
|
||||
Code: code,
|
||||
Message: http.StatusText(status),
|
||||
RequestID: requestID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func ExtractBearerToken(r *http.Request) (string, bool) {
|
||||
scheme, token, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok ||
|
||||
!strings.EqualFold(scheme, "Bearer") ||
|
||||
token == "" ||
|
||||
strings.ContainsAny(token, " \t\r\n") {
|
||||
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func FormatTime(t time.Time) string {
|
||||
return t.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
func CheckIdempotencyKeyPattern(key string) bool {
|
||||
patternReg := regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
return patternReg.MatchString(key)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Middleware struct {
|
||||
authService *service.AuthService
|
||||
instanceID string
|
||||
}
|
||||
|
||||
func NewMiddleware(authService *service.AuthService, instanceID string) *Middleware {
|
||||
|
||||
return &Middleware{
|
||||
authService: authService,
|
||||
instanceID: instanceID,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (m *Middleware) Auth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := RequestIDFromContext(r.Context())
|
||||
|
||||
token, ok := httputils.ExtractBearerToken(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := m.authService.ValidateSession(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := WithUserID(r.Context(), userID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := uuid.NewString()
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
ctx := WithRequestID(r.Context(), requestID)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) InstanceID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", m.instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import "context"
|
||||
|
||||
// UserID
|
||||
type contextKey string
|
||||
|
||||
const userIDKey contextKey = "userID"
|
||||
|
||||
func WithUserID(ctx context.Context, userID string) context.Context {
|
||||
return context.WithValue(ctx, userIDKey, userID)
|
||||
}
|
||||
|
||||
func UserIDFromContext(ctx context.Context) string {
|
||||
userID, _ := ctx.Value(userIDKey).(string)
|
||||
return userID
|
||||
}
|
||||
|
||||
// RequestIDKey
|
||||
const requestIDKey contextKey = "requestID"
|
||||
|
||||
func RequestIDFromContext(ctx context.Context) string {
|
||||
requestID, _ := ctx.Value(requestIDKey).(string)
|
||||
return requestID
|
||||
}
|
||||
|
||||
func WithRequestID(ctx context.Context, requestID string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey, requestID)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type responseWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (m *Middleware) Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
rw := &responseWriter{
|
||||
ResponseWriter: w,
|
||||
status: http.StatusOK,
|
||||
}
|
||||
|
||||
next.ServeHTTP(rw, r)
|
||||
|
||||
slog.Info(
|
||||
"http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", rw.status,
|
||||
"duration", time.Since(start),
|
||||
"request_id", RequestIDFromContext(r.Context()),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Router struct {
|
||||
middleware *middleware.Middleware
|
||||
authHandler *handler.AuthHandler
|
||||
healthHandler *handler.HealthHandler
|
||||
chatHandler *handler.ChatHandler
|
||||
userHandler *handler.UserHandler
|
||||
messageHandler *handler.MessageHandler
|
||||
}
|
||||
|
||||
func NewRouter(middleware *middleware.Middleware, authHandler *handler.AuthHandler, healthHandler *handler.HealthHandler, chatHandler *handler.ChatHandler, userHandler *handler.UserHandler, messageHandler *handler.MessageHandler) *Router {
|
||||
return &Router{chatHandler: chatHandler, authHandler: authHandler, healthHandler: healthHandler, middleware: middleware, userHandler: userHandler, messageHandler: messageHandler}
|
||||
}
|
||||
|
||||
func (r *Router) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
protectedMux := http.NewServeMux()
|
||||
|
||||
protectedMux.HandleFunc("/", r.healthHandler.NotFoundRoute)
|
||||
mux.HandleFunc("GET /health/live", r.healthHandler.Live)
|
||||
mux.HandleFunc("GET /health/ready", r.healthHandler.Ready)
|
||||
|
||||
//Auth
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", r.authHandler.CreateSession)
|
||||
protectedMux.HandleFunc("DELETE /api/v1/auth/sessions/current", r.authHandler.DeleteSession)
|
||||
|
||||
//User
|
||||
mux.HandleFunc("POST /api/v1/users", r.userHandler.CreateUser)
|
||||
protectedMux.HandleFunc("GET /api/v1/users/me", r.userHandler.GetCurrentUser)
|
||||
|
||||
//Chat
|
||||
protectedMux.HandleFunc("POST /api/v1/chats", r.chatHandler.CreateChat)
|
||||
protectedMux.HandleFunc("GET /api/v1/chats", r.chatHandler.GetChatsByUserID)
|
||||
protectedMux.HandleFunc("GET /api/v1/chats/{chat_id}", r.chatHandler.GetChatByChatID)
|
||||
|
||||
//Message
|
||||
protectedMux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", r.messageHandler.CreateMessage)
|
||||
protectedMux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", r.messageHandler.GetMessagesByChatID)
|
||||
|
||||
mux.Handle("/api/v1/", r.middleware.Auth(protectedMux))
|
||||
return r.middleware.InstanceID(r.middleware.RequestID(
|
||||
r.middleware.Logging(mux),
|
||||
))
|
||||
}
|
||||
Reference in New Issue
Block a user