From 7c32f1aad2eb6d921d94e04d8bdeb1a9afbc5d17 Mon Sep 17 00:00:00 2001 From: Nicolai Ort Date: Thu, 12 Dec 2024 17:34:55 +0100 Subject: [PATCH] perf(templates): Cache templates in map --- main.go | 4 +++- services/templates.go | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index fbbd306..8562d23 100644 --- a/main.go +++ b/main.go @@ -74,7 +74,9 @@ func main() { } barcodeGenerator := &services.DefaultBarcodeService{} - staticService := &services.DefaultStaticService{} + staticService := &services.DefaultStaticService{ + Cache: make(map[string]string), + } handler := handlers.DefaultHandler{ Config: config, BarcodeService: barcodeGenerator, diff --git a/services/templates.go b/services/templates.go index 92230b6..2799305 100644 --- a/services/templates.go +++ b/services/templates.go @@ -14,14 +14,24 @@ type StaticService interface { } type DefaultStaticService struct { + Cache map[string]string } func (s *DefaultStaticService) GetTemplate(locale, templateName string) (string, error) { + + if s.Cache[locale+templateName] != "" { + log.Printf("returning cached template %s with locale %s", templateName, locale) + return s.Cache[locale+templateName], nil + } + content, err := os.ReadFile(fmt.Sprintf("static/templates/%s/%s.html", templateName, locale)) if content == nil || err != nil { log.Printf("error reading template %s with locale %s: %v", templateName, locale, err) return "", err } + + s.Cache[locale+templateName] = string(content) + return string(content), nil }