hikan.ru/mvc/controllers/controllers_pages/posts.go

54 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package controllers_pages
import (
"main/mvc/models"
"main/mvc/models/models_pages"
"net/http"
"path"
"strconv"
)
// Обработчик странички со списком постов
func PostsPageHandler(app *models.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
link := r.URL.Path
cacheKey := link
ajax := r.URL.Query().Get("ajax") == "true"
if ajax {
cacheKey += "?ajax=true"
}
if pageData, ok := app.PagesCache.Get(cacheKey); ok {
sendPostsPage(w, pageData)
return
}
postsList := app.PostsMap.PostsList()
pageNumber, _ := strconv.Atoi(path.Base(link))
page := models_pages.CreatePostsPage(postsList, pageNumber, app.Cfg.PostsMaxCountOnPage)
var (
pageData []byte
err error
)
pageData, err = page.RenderPostsPage(app.Templates, app.Version, ajax)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
app.PagesCache.Set(cacheKey, pageData)
sendPostsPage(w, pageData)
}
}
// Отправляет страницу
func sendPostsPage(w http.ResponseWriter, data []byte) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(data)
}