modified: serv_nginx/api_bb/internal/handlers/avatar.go

modified:   serv_nginx/api_bb/internal/handlers/handlers.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
	modified:   serv_nginx/nginx/nginx-ssl.conf
try to serve file name throught path
This commit is contained in:
2025-10-14 12:41:16 +05:00
parent 46549f5d22
commit bbf470617b
6 changed files with 226 additions and 30 deletions
+34 -1
View File
@@ -6,6 +6,8 @@ import (
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"time"
"api_bb/internal/models"
@@ -35,6 +37,7 @@ func (h *UserHandler) Routes() chi.Router {
r.Get("/profile", h.GetProfile)
r.Post("/editProfile", h.UpdateProfile)
r.Get("/avatar/{filename}", h.ServeAvatar)
return r
}
@@ -54,7 +57,6 @@ type UserResponse struct {
UpdatedAt time.Time `json:"updated_at"`
}
func (h *UserHandler) GetProfile(w http.ResponseWriter, r *http.Request) {
h.logger.Info("handling get profile request",
@@ -176,3 +178,34 @@ func (h *UserHandler) UpdateProfile(w http.ResponseWriter, r *http.Request) {
"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),
)
// Используем http.ServeFile для эффективной отдачи файла
avatarPath := filepath.Join("./uploads/avatars", filename)
// Проверяем существование файла
if _, err := os.Stat(avatarPath); os.IsNotExist(err) {
h.logger.Warn("avatar file not found", zap.String("path", avatarPath))
utils.RespondWithError(w, http.StatusNotFound, "Avatar not found")
return
}
// Устанавливаем заголовки кэширования
w.Header().Set("Cache-Control", "public, max-age=31536000")
w.Header().Set("Expires", time.Now().Add(365*24*time.Hour).Format(http.TimeFormat))
// Отдаем файл
http.ServeFile(w, r, avatarPath)
h.logger.Info("avatar served via ServeFile",
zap.String("filename", filename),
)
}