modified: serv_nginx/api_bb/internal/handlers/avatar.go
modified: serv_nginx/api_bb/internal/handlers/user.go modified: serv_nginx/api_bb/internal/routes/routes.go modified: serv_nginx/api_bb/internal/service/avatar_service.go set all avatars manipulating into avatar.go and remove from user.go
This commit is contained in:
@@ -4,12 +4,8 @@ package handlers
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"api_bb/internal/models"
|
||||
@@ -39,8 +35,7 @@ func (h *UserHandler) Routes() chi.Router {
|
||||
|
||||
r.Get("/profile", h.GetProfile)
|
||||
r.Post("/editProfile", h.UpdateProfile)
|
||||
r.Get("/avatars/{filename}", h.ServeAvatar)
|
||||
|
||||
// Убрали маршрут для обслуживания аватаров - теперь это делает AvatarHandler
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -179,74 +174,4 @@ func (h *UserHandler) UpdateProfile(w http.ResponseWriter, r *http.Request) {
|
||||
"message": "Profile updated successfully",
|
||||
"user": toUserResponse(updatedUser),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *UserHandler) ServeAvatar(w http.ResponseWriter, r *http.Request) {
|
||||
filename := chi.URLParam(r, "filename")
|
||||
|
||||
h.logger.Info("handling serve avatar request",
|
||||
zap.String("method", r.Method),
|
||||
zap.String("filename", filename),
|
||||
zap.String("remote_addr", r.RemoteAddr),
|
||||
)
|
||||
|
||||
// Валидация
|
||||
if filename == "" || strings.Contains(filename, "..") || strings.Contains(filename, "/") {
|
||||
utils.RespondWithError(w, http.StatusBadRequest, "Invalid filename")
|
||||
return
|
||||
}
|
||||
|
||||
avatarPath := filepath.Join("./uploads/avatars", filename)
|
||||
|
||||
// Проверяем существование файла
|
||||
fileInfo, err := os.Stat(avatarPath)
|
||||
if os.IsNotExist(err) {
|
||||
h.logger.Warn("avatar file not found", zap.String("path", avatarPath))
|
||||
utils.RespondWithError(w, http.StatusNotFound, "Avatar not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Error("failed to access file", zap.Error(err))
|
||||
utils.RespondWithError(w, http.StatusInternalServerError, "File access error")
|
||||
return
|
||||
}
|
||||
|
||||
// Открываем файл
|
||||
file, err := os.Open(avatarPath)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to open file", zap.Error(err))
|
||||
utils.RespondWithError(w, http.StatusInternalServerError, "File open error")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Определяем Content-Type
|
||||
ext := strings.ToLower(filepath.Ext(filename))
|
||||
contentType := "application/octet-stream"
|
||||
switch ext {
|
||||
case ".png": contentType = "image/png"
|
||||
case ".jpg", ".jpeg": contentType = "image/jpeg"
|
||||
case ".gif": contentType = "image/gif"
|
||||
case ".webp": contentType = "image/webp"
|
||||
}
|
||||
|
||||
// ✅ Устанавливаем ВСЕ заголовки
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000") // 1 год
|
||||
w.Header().Set("Last-Modified", fileInfo.ModTime().Format(http.TimeFormat))
|
||||
|
||||
// Копируем файл в ResponseWriter
|
||||
_, err = io.Copy(w, file)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to send file", zap.Error(err))
|
||||
// Не отправляем ошибку - соединение уже испорчено
|
||||
return
|
||||
}
|
||||
|
||||
h.logger.Info("avatar served successfully",
|
||||
zap.String("filename", filename),
|
||||
zap.String("content_type", contentType),
|
||||
zap.Int64("file_size", fileInfo.Size()),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user