2020-07-31 13:48:01 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2020-07-31 17:46:12 +00:00
|
|
|
"bytes"
|
2020-07-31 19:02:47 +00:00
|
|
|
"fmt"
|
2020-07-31 13:48:01 +00:00
|
|
|
"html/template"
|
|
|
|
"log"
|
2020-07-31 17:46:12 +00:00
|
|
|
"net/http"
|
2020-07-31 13:48:01 +00:00
|
|
|
)
|
|
|
|
|
2020-07-31 19:02:47 +00:00
|
|
|
const templatePost = "post"
|
|
|
|
const templateError = "error"
|
|
|
|
const templateRedirect = "redirect"
|
2020-07-31 13:48:01 +00:00
|
|
|
|
2020-07-31 19:02:47 +00:00
|
|
|
var templates map[string]*template.Template
|
|
|
|
var templateFunctions template.FuncMap
|
2020-07-31 13:48:01 +00:00
|
|
|
|
|
|
|
func initRendering() {
|
2020-07-31 19:02:47 +00:00
|
|
|
templateFunctions = template.FuncMap{
|
2020-07-31 13:48:01 +00:00
|
|
|
"blog": func() *configBlog {
|
2020-08-04 17:42:09 +00:00
|
|
|
return appConfig.Blog
|
2020-07-31 13:48:01 +00:00
|
|
|
},
|
|
|
|
"md": func(content string) template.HTML {
|
|
|
|
htmlContent, err := renderMarkdown(content)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return template.HTML(htmlContent)
|
|
|
|
},
|
2020-07-31 19:02:47 +00:00
|
|
|
"p": func(post Post, parameter string) string {
|
|
|
|
return post.Parameters[parameter]
|
2020-07-31 13:48:01 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2020-07-31 19:02:47 +00:00
|
|
|
templates = make(map[string]*template.Template)
|
|
|
|
for _, name := range []string{templatePost, templateError, templateRedirect} {
|
|
|
|
templates[name] = loadTemplate(name)
|
2020-07-31 13:48:01 +00:00
|
|
|
}
|
|
|
|
}
|
2020-07-31 17:46:12 +00:00
|
|
|
|
2020-07-31 19:02:47 +00:00
|
|
|
func loadTemplate(name string) *template.Template {
|
|
|
|
return template.Must(template.New(name).Funcs(templateFunctions).ParseFiles("templates/base.gohtml", fmt.Sprintf("templates/%s.gohtml", name)))
|
|
|
|
}
|
|
|
|
|
2020-07-31 17:46:12 +00:00
|
|
|
func render(w http.ResponseWriter, template string, data interface{}) {
|
|
|
|
// We need to use a buffer here to enable minification
|
|
|
|
var buffer bytes.Buffer
|
2020-07-31 19:02:47 +00:00
|
|
|
err := templates[template].ExecuteTemplate(&buffer, template, data)
|
2020-07-31 17:46:12 +00:00
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
// Set content type (needed for minification middleware
|
|
|
|
w.Header().Set("Content-Type", contentTypeHTML)
|
|
|
|
// Write buffered response
|
|
|
|
_, _ = w.Write(buffer.Bytes())
|
|
|
|
}
|