92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"gitea.d3m0k1d.ru/d3m0k1d/d3m0k1d.ru/backend/internal/logger"
|
|
"gitea.d3m0k1d.ru/d3m0k1d/d3m0k1d.ru/backend/internal/models"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type StaticHandlers struct {
|
|
logger *logger.Logger
|
|
}
|
|
|
|
func NewStaticHandlers() *StaticHandlers {
|
|
return &StaticHandlers{
|
|
logger: logger.New(false),
|
|
}
|
|
}
|
|
|
|
// PostStatic godoc
|
|
// @Summary Upload static content
|
|
// @Description Upload static content to the server
|
|
// @Tags static
|
|
// @Produce json
|
|
// @Success 200 {object} models.SuccessResponse(data=string) "Static content"
|
|
// @Failure 500 {object} models.ErrorResponse "Internal server error"
|
|
// @Router /upload [post]
|
|
func (h *StaticHandlers) PostStatic(c *gin.Context) {
|
|
content, err := c.FormFile("file")
|
|
if err != nil {
|
|
h.logger.Error("error request: " + err.Error())
|
|
models.Error(c, 500, "Internal server error", err.Error())
|
|
return
|
|
}
|
|
dst := "/data/upload/" + content.Filename
|
|
if err = c.SaveUploadedFile(content, dst); err != nil {
|
|
h.logger.Error("error request: " + err.Error())
|
|
models.Error(c, 500, "Internal server error", err.Error())
|
|
return
|
|
}
|
|
models.Success(c, "Static content saved")
|
|
}
|
|
|
|
// GetStatic godoc
|
|
// @Summary Get static content
|
|
// @Description Get static content
|
|
// @Tags static
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param file path string true "File name"
|
|
// @Success 200 {object} models.SuccessResponse{data=string} "Static content"
|
|
// @Failure 500 {object} models.ErrorResponse "Internal server error"
|
|
// @Failure 404 {object} models.ErrorResponse "File not found"
|
|
// @Router /upload/{file} [get]
|
|
func (h *StaticHandlers) GetStatic(c *gin.Context) {
|
|
|
|
filename := c.Param("file")
|
|
if filename == "" {
|
|
models.Error(c, 404, "File not found", "")
|
|
return
|
|
}
|
|
|
|
filename = filepath.Clean(filename)
|
|
|
|
if strings.Contains(filename, "..") {
|
|
models.Error(c, 400, "Invalid file path", "")
|
|
return
|
|
}
|
|
|
|
if filepath.IsAbs(filename) {
|
|
models.Error(c, 400, "Invalid file path", "")
|
|
return
|
|
}
|
|
|
|
baseDir := "/data/upload/"
|
|
fullPath := filepath.Join(baseDir, filename)
|
|
if !strings.HasPrefix(fullPath, baseDir) {
|
|
models.Error(c, 400, "Invalid file path", "")
|
|
return
|
|
}
|
|
|
|
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
|
|
models.Error(c, 404, "File not found", "")
|
|
return
|
|
}
|
|
|
|
c.File(fullPath)
|
|
}
|