GoBlog/render.go

252 lines
6.5 KiB
Go
Raw Normal View History

2020-07-31 13:48:01 +00:00
package main
import (
"bytes"
2021-01-21 16:59:47 +00:00
"encoding/json"
2020-11-01 17:37:21 +00:00
"errors"
2020-10-13 11:40:16 +00:00
"fmt"
2020-07-31 13:48:01 +00:00
"html/template"
"log"
"net/http"
2021-05-08 19:22:48 +00:00
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
2020-10-06 17:07:48 +00:00
"github.com/araddon/dateparse"
2021-03-10 17:47:56 +00:00
servertiming "github.com/mitchellh/go-server-timing"
2020-07-31 13:48:01 +00:00
)
const (
templatesDir = "templates"
templatesExt = ".gohtml"
templateBase = "base"
templatePost = "post"
templateError = "error"
templateIndex = "index"
templateTaxonomy = "taxonomy"
templateSearch = "search"
templateSummary = "summary"
templatePhotosSummary = "photosummary"
templateEditor = "editor"
templateLogin = "login"
templateStaticHome = "statichome"
templateBlogStats = "blogstats"
templateBlogStatsTable = "blogstatstable"
templateComment = "comment"
templateCaptcha = "captcha"
templateCommentsAdmin = "commentsadmin"
templateNotificationsAdmin = "notificationsadmin"
2021-02-20 22:35:16 +00:00
templateWebmentionAdmin = "webmentionadmin"
2021-05-08 19:22:48 +00:00
templateBlogroll = "blogroll"
)
2020-07-31 13:48:01 +00:00
2021-03-11 08:16:19 +00:00
var templates map[string]*template.Template = map[string]*template.Template{}
2020-07-31 13:48:01 +00:00
func initRendering() error {
2021-03-11 08:16:19 +00:00
templateFunctions := template.FuncMap{
2020-10-12 16:47:23 +00:00
"menu": func(blog *configBlog, id string) *menu {
return blog.Menus[id]
2020-09-19 11:37:58 +00:00
},
2020-11-01 17:37:21 +00:00
"user": func() *configUser {
return appConfig.User
},
2020-07-31 13:48:01 +00:00
"md": func(content string) template.HTML {
htmlContent, err := renderMarkdown(content, false)
2020-07-31 13:48:01 +00:00
if err != nil {
log.Fatal(err)
return ""
}
return template.HTML(htmlContent)
},
2021-02-03 09:44:39 +00:00
"html": func(s string) template.HTML {
return template.HTML(s)
},
2020-10-18 09:54:29 +00:00
// Post specific
2020-10-15 15:32:46 +00:00
"p": func(p *post, parameter string) string {
return p.firstParameter(parameter)
2020-08-31 19:12:43 +00:00
},
2020-10-15 15:32:46 +00:00
"ps": func(p *post, parameter string) []string {
return p.Parameters[parameter]
2020-07-31 13:48:01 +00:00
},
"hasp": func(p *post, parameter string) bool {
return len(p.Parameters[parameter]) > 0
},
2020-10-15 15:32:46 +00:00
"title": func(p *post) string {
return p.title()
2020-09-02 15:48:37 +00:00
},
2020-10-18 09:54:29 +00:00
"content": func(p *post) template.HTML {
return p.html()
},
2020-10-15 15:32:46 +00:00
"summary": func(p *post) string {
return p.summary()
},
"translations": func(p *post) []*post {
return p.translations()
},
2020-12-22 21:15:29 +00:00
"shorturl": func(p *post) string {
return p.shortURL()
},
// Others
"dateformat": dateFormat,
"isodate": func(date string) string {
return dateFormat(date, "2006-01-02")
2020-10-12 17:46:14 +00:00
},
"unixtodate": func(unix int64) string {
2020-12-16 20:24:53 +00:00
return time.Unix(unix, 0).Local().String()
},
2020-11-01 17:37:21 +00:00
"now": func() string {
2020-12-16 20:24:53 +00:00
return time.Now().Local().String()
2020-11-01 17:37:21 +00:00
},
2020-11-03 17:00:03 +00:00
"dateadd": func(date string, years, months, days int) string {
2020-12-16 19:21:35 +00:00
d, err := dateparse.ParseLocal(date)
2020-11-03 17:00:03 +00:00
if err != nil {
return ""
}
2020-12-16 20:24:53 +00:00
return d.AddDate(years, months, days).Local().String()
2020-11-03 17:00:03 +00:00
},
"datebefore": func(date string, before string) bool {
2020-12-16 19:21:35 +00:00
d, err := dateparse.ParseLocal(date)
2020-11-03 17:00:03 +00:00
if err != nil {
return false
}
2020-12-16 19:21:35 +00:00
b, err := dateparse.ParseLocal(before)
2020-11-03 17:00:03 +00:00
if err != nil {
return false
}
return d.Before(b)
},
"asset": assetFileName,
"assetsri": assetSRI,
"string": getTemplateStringVariant,
2020-11-01 17:37:21 +00:00
"include": func(templateName string, data ...interface{}) (template.HTML, error) {
2021-03-10 18:21:23 +00:00
if len(data) == 0 || len(data) > 2 {
return "", errors.New("wrong argument count")
}
if rd, ok := data[0].(*renderData); ok {
if len(data) == 2 {
nrd := *rd
nrd.Data = data[1]
rd = &nrd
2020-11-01 17:37:21 +00:00
}
2021-03-10 21:31:43 +00:00
var buf bytes.Buffer
err := templates[templateName].ExecuteTemplate(&buf, templateName, rd)
2021-03-10 18:21:23 +00:00
return template.HTML(buf.String()), err
2020-11-01 17:37:21 +00:00
}
2021-03-10 18:21:23 +00:00
return "", errors.New("wrong arguments")
2020-11-01 17:37:21 +00:00
},
2020-09-01 16:53:21 +00:00
"urlize": urlize,
2020-09-19 12:56:31 +00:00
"sort": sortedStrings,
2020-11-01 17:37:21 +00:00
"absolute": func(path string) string {
return appConfig.Server.PublicAddress + path
},
2020-11-03 17:00:03 +00:00
"blogrelative": func(blog *configBlog, path string) string {
return blog.getRelativePath(path)
2020-10-12 17:26:32 +00:00
},
"jsonFile": func(filename string) *map[string]interface{} {
parsed := &map[string]interface{}{}
2021-02-17 07:23:03 +00:00
content, err := os.ReadFile(filename)
2020-10-13 11:40:16 +00:00
if err != nil {
return nil
}
err = json.Unmarshal(content, parsed)
2020-10-13 11:40:16 +00:00
if err != nil {
fmt.Println(err.Error())
return nil
}
return parsed
2020-10-13 11:40:16 +00:00
},
2021-02-14 13:15:01 +00:00
"mentions": func(absolute string) []*mention {
mentions, _ := getWebmentions(&webmentionsRequestConfig{
target: absolute,
status: webmentionStatusApproved,
asc: true,
})
return mentions
},
2021-05-08 19:22:48 +00:00
"urlToString": func(u url.URL) string {
return u.String()
},
2020-07-31 13:48:01 +00:00
}
2021-03-11 08:16:19 +00:00
baseTemplate, err := template.New("base").Funcs(templateFunctions).ParseFiles(path.Join(templatesDir, templateBase+templatesExt))
if err != nil {
return err
}
err = filepath.Walk(templatesDir, func(p string, info os.FileInfo, err error) error {
2021-02-08 17:51:07 +00:00
if err != nil {
return err
}
if info.Mode().IsRegular() && path.Ext(p) == templatesExt {
2021-02-08 17:51:07 +00:00
if name := strings.TrimSuffix(path.Base(p), templatesExt); name != templateBase {
2021-03-11 08:16:19 +00:00
if templates[name], err = template.Must(baseTemplate.Clone()).New(name).ParseFiles(p); err != nil {
return err
}
}
}
return nil
2021-03-11 08:16:19 +00:00
})
if err != nil {
return err
}
return nil
}
2020-10-12 16:47:23 +00:00
type renderData struct {
BlogString string
Canonical string
Blog *configBlog
Data interface{}
LoggedIn bool
CommentsEnabled bool
WebmentionReceivingEnabled bool
2020-10-12 16:47:23 +00:00
}
2021-02-20 22:35:16 +00:00
func render(w http.ResponseWriter, r *http.Request, template string, data *renderData) {
2021-03-10 17:47:56 +00:00
// Server timing
t := servertiming.FromContext(r.Context()).NewMetric("r").Start()
2020-10-12 16:47:23 +00:00
// Check render data
if data.Blog == nil {
2021-01-17 11:53:07 +00:00
if len(data.BlogString) == 0 {
data.BlogString = appConfig.DefaultBlog
}
data.Blog = appConfig.Blogs[data.BlogString]
}
if data.BlogString == "" {
for s, b := range appConfig.Blogs {
if b == data.Blog {
data.BlogString = s
break
}
2020-10-12 16:47:23 +00:00
}
}
if data.Data == nil {
data.Data = map[string]interface{}{}
}
2021-02-20 22:35:16 +00:00
// Check login
if loggedIn, ok := r.Context().Value(loggedInKey).(bool); ok && loggedIn {
data.LoggedIn = true
}
// Check if comments enabled
data.CommentsEnabled = data.Blog.Comments != nil && data.Blog.Comments.Enabled
// Check if able to receive webmentions
data.WebmentionReceivingEnabled = appConfig.Webmention == nil || !appConfig.Webmention.DisableReceiving
2021-02-20 22:35:16 +00:00
// Minify and write response
mw := minifier.Writer(contentTypeHTML, w)
defer func() {
_ = mw.Close()
}()
err := templates[template].ExecuteTemplate(mw, template, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
2020-11-22 19:30:02 +00:00
return
}
// Set content type
2020-10-06 17:07:48 +00:00
w.Header().Set(contentType, contentTypeHTMLUTF8)
2021-03-10 17:47:56 +00:00
// Server timing
t.Stop()
}