aboutsummaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
authorHenrique Dias <hacdias@gmail.com>2023-11-10 14:23:27 +0100
committerGitHub <noreply@github.com>2023-11-10 05:23:27 -0800
commitbcddd3bbbea1a64a3fa9d71254f143246116b5b3 (patch)
tree9954499e5a916a1b1a1b1f67d06656e832b4b871 /main.go
parenta068bd4dd4b5040bd7b8ac514b32d3141f882b8a (diff)
downloadsally-bcddd3bbbea1a64a3fa9d71254f143246116b5b3.tar.gz
feat: support for custom templates (#129)
Adds a `-templates` flag that can be used to provide an alternative directory with templates for Sally to use. The new templates override the default set embedded in Sally. This includes a new 404 template so that 404 errors use the same theme as the rest of the website. Additionally, for HTTP status >400, this also sets the Cache-Control header to discourage CDNs like Cloudflare from caching the page. Resolves #125, #18
Diffstat (limited to '')
-rw-r--r--main.go30
1 files changed, 29 insertions, 1 deletions
diff --git a/main.go b/main.go
index 5d54071..522ecf8 100644
--- a/main.go
+++ b/main.go
@@ -5,12 +5,15 @@ package main // import "go.uber.org/sally"
import (
"flag"
"fmt"
+ "html/template"
"log"
"net/http"
+ "path/filepath"
)
func main() {
yml := flag.String("yml", "sally.yaml", "yaml file to read config from")
+ tpls := flag.String("templates", "", "directory of .html templates to use")
port := flag.Int("port", 8080, "port to listen and serve on")
flag.Parse()
@@ -20,9 +23,34 @@ func main() {
log.Fatalf("Failed to parse %s: %v", *yml, err)
}
+ var templates *template.Template
+ if *tpls != "" {
+ log.Printf("Parsing templates at path: %s\n", *tpls)
+ templates, err = getCombinedTemplates(*tpls)
+ if err != nil {
+ log.Fatalf("Failed to parse templates at %s: %v", *tpls, err)
+ }
+ } else {
+ templates = _templates
+ }
+
log.Printf("Creating HTTP handler with config: %v", config)
- handler := CreateHandler(config)
+ handler, err := CreateHandler(config, templates)
+ if err != nil {
+ log.Fatalf("Failed to create handler: %v", err)
+ }
log.Printf(`Starting HTTP handler on ":%d"`, *port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), handler))
}
+
+func getCombinedTemplates(dir string) (*template.Template, error) {
+ // Clones default templates to then merge with the user defined templates.
+ // This allows for the user to only override certain templates, but not all
+ // if they don't want.
+ templates, err := _templates.Clone()
+ if err != nil {
+ return nil, err
+ }
+ return templates.ParseGlob(filepath.Join(dir, "*.html"))
+}