hikan.ru/mvc/controllers/cache.go

80 lines
2.3 KiB
Go
Raw Normal View History

2025-02-02 16:43:55 +03:00
package controllers
import (
"fmt"
"main/mvc/models"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
)
type DeleteFromCacheRequest struct {
Cachekey string `form:"cachekey" json:"cachekey"`
}
func DeleteFromCache(tmplname string, group *gin.RouterGroup, s *models.Site) {
group.POST(fmt.Sprintf("/%s", tmplname), func(c *gin.Context) {
var requestData DeleteFromCacheRequest
// Привязка данных формы к структуре
if err := c.ShouldBind(&requestData); err != nil {
c.Redirect(http.StatusFound, "/index/1?Ошибка при привязке данных к структуре")
return
}
s.Cache.Delete(requestData.Cachekey)
c.Redirect(http.StatusFound, "/adm/1?Запись удалена из кэша")
})
}
func CacheClear(tmplname string, group *gin.RouterGroup, s *models.Site) {
group.POST(tmplname, func(c *gin.Context) {
s.Cache.Flush()
c.Redirect(http.StatusFound, "/adm/1?Кэш очищен")
})
}
func UploadCache(tmplname string, group *gin.RouterGroup, s *models.Site) {
group.POST(tmplname, func(c *gin.Context) {
file, err := c.FormFile("file-upload")
if err != nil {
c.Redirect(http.StatusFound, "/adm/1?Ошибка при получении файла")
return
}
// Открываем файл для чтения
fileReader, err := file.Open()
if err != nil {
c.Redirect(http.StatusFound, "/adm/1?Ошибка при открытии файла")
return
}
defer fileReader.Close()
// Загружаем данные в кэш
if err := s.Cache.Load(fileReader); err != nil {
c.Redirect(http.StatusFound, "/adm/1?Ошибка при загрузке данных в кэш")
return
}
c.Redirect(http.StatusFound, "/adm/1?Дамп успешно загружен")
})
}
func DownloadCache(group *gin.RouterGroup, s *models.Site) {
group.GET("/loadcachedump", func(c *gin.Context) {
path := "cache.json"
if err := models.WriteCacheDumpToFile(s.Cache, path); err != nil {
s.Bot.SendMessage(fmt.Sprintf("🔴 Ошибка записи дампа кэша в файл: %s", err.Error()))
} else {
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%d%s", time.Now().Unix(), path))
c.Header("Content-Type", "application/octet-stream")
c.File(path)
}
os.Remove(path)
})
}