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

48 lines
1.3 KiB
Go
Raw Permalink 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"
"strings"
)
// Обработчик главной страницы
func PostPageHandler(app *models.App) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var err error
postLink := r.URL.Path
// Ссылки на посты имеют вид postLink = /link/, а если прилетело что то типо /link/123123,
// то надо оставить только часть /link/
secondSlash := strings.IndexByte(postLink[1:], '/')
if secondSlash != -1 {
postLink = postLink[:secondSlash+2]
}
// Страничка рендерится только если ее нет в кэше
pageData, ok := app.PagesCache.Get(postLink)
if !ok {
post := app.Posts[models_pages.PostLink(postLink)]
pageData, err = models_pages.RenderPostPage(app.Templates, app.Version, post.Data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
app.PagesCache.Set(postLink, pageData)
}
sendPostPage(w, pageData)
})
}
// Отправляет страницу
func sendPostPage(w http.ResponseWriter, data []byte) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(data)
}