Files
fnx_web/webcontroller/templates.go

62 lines
1.7 KiB
Go
Raw Normal View History

2019-12-23 23:56:57 +01:00
package webcontroller
import (
"encoding/json"
2019-12-23 23:56:57 +01:00
"html/template"
"net/http"
"time"
2021-11-16 15:20:15 +01:00
"fornaxian.tech/log"
2021-11-02 16:28:02 +01:00
"fornaxian.tech/util"
2019-12-23 23:56:57 +01:00
)
// TemplateData is the data for the page template, res/template/wrap.html
2019-12-23 23:56:57 +01:00
type TemplateData struct {
APIEndpoint template.URL
Hostname template.HTML
CacheID int64
2019-12-23 23:56:57 +01:00
// Describe the site by default, or the file on a filesystem page
2019-12-23 23:56:57 +01:00
Title string
2020-12-07 22:23:29 +01:00
OGData ogData
2019-12-23 23:56:57 +01:00
// Embedded in the page as window.user and window.initial_node, so the JS
// doesn't have to request them. Left empty when they were not requested
User json.RawMessage
Node json.RawMessage
2019-12-23 23:56:57 +01:00
}
2022-10-11 14:42:24 +02:00
// The cache ID is used to invalidate caches when the webserver is restarted.
// It's rounded to a full hour to prevent cached from being emptied too often if
// the server is regularly restarted
var cacheID = time.Now().Unix() / 3600
func (wc *WebController) newTemplateData(r *http.Request) *TemplateData {
return &TemplateData{
APIEndpoint: template.URL(wc.config.APIURLExternal),
Hostname: template.HTML(wc.hostname),
CacheID: cacheID,
Title: "Nova.storage",
OGData: siteOGData(r),
2019-12-23 23:56:57 +01:00
}
}
2020-08-28 13:44:50 +02:00
func (wc *WebController) parseTemplate() *template.Template {
return template.Must(template.ParseFiles(wc.config.ResourceDir + "/template/wrap.html"))
2019-12-23 23:56:57 +01:00
}
2024-09-09 23:59:04 +02:00
// renderPage writes the page which loads the Svelte app. In debug mode the
// template is parsed on every request, so changes show up without a restart
func (wc *WebController) renderPage(w http.ResponseWriter, r *http.Request, td *TemplateData) {
var tpl = wc.tpl
if wc.config.DebugMode {
tpl = wc.parseTemplate()
2020-08-28 13:44:50 +02:00
}
if r.Method == "HEAD" {
return
2019-12-23 23:56:57 +01:00
}
if err := tpl.Execute(w, td); err != nil && !util.IsNetError(err) {
log.Error("Error executing page template: %s", err)
2021-09-07 17:09:52 +02:00
}
}