Files
RenewCMS/api/page.go
T
Florian Sylvain 7d071ebc2e clean: refactor templates to use a common head section
This commit introduces a refactoring in various page templates to use a central, common 'head' section, stored under utilsHead.html. This head section contains common metadata, styles, and scripts. This change enhances code reusability and standardizes the head section across different pages for consistent user experience and ease of future potential changes. Also, some minimal adjustments were made in the navigation and link routing for more user-friendly URL paths. Lastly, the server's listening interface was updated to only listen on the localhost.
2023-10-11 20:28:00 +02:00

102 lines
2.3 KiB
Go

package api
import (
"embed"
"github.com/go-chi/chi/v5"
"html/template"
"io/fs"
"net/http"
"path/filepath"
"strings"
)
//go:embed static
var staticFolder embed.FS
var headTmpl template.HTML
var contentTypes = map[string]string{
".css": "text/css",
".js": "application/javascript",
".png": "image/png",
".jpg": "image/jpeg",
".webp": "image/webp",
".svg": "image/svg+xml",
".ico": "image/x-icon",
}
type PageError struct {
Message string `json:"message"`
IsError bool `json:"isError"`
}
func NewPageError(message string) *PageError {
return &PageError{
Message: message,
IsError: strings.Compare(message, "") != 0,
}
}
func IsLoggedInMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !IsLoggedIn(r) {
http.Redirect(w, r, LoginRoute, http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
func GetLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, LoginRoute, http.StatusPermanentRedirect)
}
func GetLogout(w http.ResponseWriter, r *http.Request) {
RemoveJwtCookie(w)
http.Redirect(w, r, LoginRoute, http.StatusSeeOther)
}
func StaticFileServerWithContentType(fsys http.FileSystem) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if ext := filepath.Ext(path); ext != "" {
if ct, ok := contentTypes[ext]; ok {
w.Header().Set("Content-Type", ct)
}
}
http.FileServer(fsys).ServeHTTP(w, r)
})
}
func InitHeadTmpl() {
headTmplHtml, _ := Container.GetPageUseCase.GetPage("utilsHead", nil)
headTmpl = template.HTML(headTmplHtml)
}
func NewPageRouter() http.Handler {
r := chi.NewRouter()
contentStatic := fs.FS(staticFolder)
InitHeadTmpl()
r.Handle("/static/*", StaticFileServerWithContentType(http.FS(contentStatic)))
r.Get("/", GetLogin)
r.Get(LoginRoute, GetLoginPageHandler(EmptyLoginPage))
r.Post(LoginRoute, GetLoginPageHandler(EmptyLoginPage))
r.Get("/register", GetRegisterPageHandler(EmptyRegisterPage))
r.Post("/register", GetRegisterPageHandler(EmptyRegisterPage))
r.Get("/logout", GetLogout)
r.Group(func(r chi.Router) {
r.Use(IsLoggedInMiddleware)
r.Get("/register-confirm", GetRegisterConfirmPage)
r.Get("/home", GetHomePage)
r.Get("/post", GetPostsPage)
r.Get("/post/edit", GetPostEditPage)
})
return r
}