From bcddd3bbbea1a64a3fa9d71254f143246116b5b3 Mon Sep 17 00:00:00 2001 From: Henrique Dias Date: Fri, 10 Nov 2023 14:23:27 +0100 Subject: 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 --- main.go | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) (limited to 'main.go') 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")) +} -- cgit v1.2.3