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
@@ -3,6 +3,7 @@ package handlers
import (
"net/http"
"time"
"api_bb/internal/service"
"api_bb/pkg/logger"
@@ -27,8 +28,12 @@ func NewAvatarHandler(avatarService service.AvatarService) *AvatarHandler {
func (h *AvatarHandler) Routes() chi.Router {
r := chi.NewRouter()
// r.Get("/avatar/{filename}", h.ServeAvatar)
r.Post("/upload", h.UploadAvatar)
r.Delete("/delete", h.DeleteAvatar)
r.Get("/{filename}", h.GetAvatar)
return r
}
@@ -99,3 +104,43 @@ func (h *AvatarHandler) DeleteAvatar(w http.ResponseWriter, r *http.Request) {
"message": "Avatar deleted successfully",
})
}
// GET /v1/user/avatar/avatar_22_1760417314.png
func (h *AvatarHandler) GetAvatar(w http.ResponseWriter, r *http.Request) {
filename := chi.URLParam(r, "filename")
h.logger.Info("handling get avatar request",
zap.String("method", r.Method),
zap.String("filename", filename),
zap.String("remote_addr", r.RemoteAddr),
)
// Вариант 1: Используем ServeAvatarFile (более эффективно для больших файлов)
contentType, err := h.avatarService.ServeAvatarFile(w, filename)
if err != nil {
h.logger.Warn("failed to serve avatar file",
zap.String("filename", filename),
zap.Error(err),
)
switch {
case err.Error() == "avatar file not found":
utils.RespondWithError(w, http.StatusNotFound, "Avatar not found")
case err.Error() == "invalid filename" || err.Error() == "unsupported file format":
utils.RespondWithError(w, http.StatusBadRequest, err.Error())
default:
utils.RespondWithError(w, http.StatusInternalServerError, "Failed to serve avatar")
}
return
}
// Устанавливаем заголовки
w.Header().Set("Content-Type", contentType)
w.Header().Set("Cache-Control", "public, max-age=31536000") // Кэш на 1 год
w.Header().Set("Expires", time.Now().Add(365*24*time.Hour).Format(http.TimeFormat))
h.logger.Info("avatar served successfully",
zap.String("filename", filename),
zap.String("content_type", contentType),
)
}