mvc upgrade

master
serr 2025-04-05 20:04:28 +03:00
parent e7c0d09456
commit a4a7db2dd7
3 changed files with 9 additions and 8 deletions

View File

@ -13,7 +13,7 @@ func MainPageHandler(a *models.App) http.HandlerFunc {
// Страничка рендерится только если ее нет в кэше // Страничка рендерится только если ее нет в кэше
pageData, ok := a.Cache.Get(models.MainPageTmplName) pageData, ok := a.Cache.Get(models.MainPageTmplName)
if !ok { if !ok {
pageData, err = a.RenderMainPage() pageData, err = models.RenderMainPage(a.Templates, a.Version)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return

View File

@ -14,14 +14,14 @@ type App struct {
Config *Config // Конфиг Config *Config // Конфиг
Templates *template.Template // Шаблоны страниц Templates *template.Template // Шаблоны страниц
Cache *Cache // Кэш (отрендеренные странички) Cache *Cache // Кэш (отрендеренные странички)
StartTime int64 // Время запуска Version int64 // Время запуска
} }
// Инициализирует приложение // Инициализирует приложение
func AppInit(configPath string) (*App, error) { func AppInit(configPath string) (*App, error) {
a := &App{ a := &App{
StartTime: time.Now().Unix(), Version: time.Now().Unix(),
Config: ConfigInit(), Config: ConfigInit(),
Cache: CacheInit(), Cache: CacheInit(),
} }

View File

@ -2,6 +2,7 @@ package models
import ( import (
"bytes" "bytes"
"html/template"
"time" "time"
) )
@ -10,15 +11,15 @@ const (
MainPageTmplName = "main_page.gohtml" MainPageTmplName = "main_page.gohtml"
) )
func (a *App) RenderMainPage() ([]byte, error) { func RenderMainPage(templates *template.Template, version int64) ([]byte, error) {
var pageData bytes.Buffer var pageData bytes.Buffer
context := map[string]any{ context := map[string]any{
"version": a.StartTime, "version": version,
"renderingTimestamp": time.Now().Unix(), "renderingTimestamp": time.Now().Unix(),
} }
if err := a.Templates.ExecuteTemplate(&pageData, MainPageTmplName, context); err != nil { if err := templates.ExecuteTemplate(&pageData, MainPageTmplName, context); err != nil {
return nil, err return nil, err
} }