Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created August 9, 2012 21:42
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanorelli/3308291 to your computer and use it in GitHub Desktop.
Save jordanorelli/3308291 to your computer and use it in GitHub Desktop.
primitive template cache in Go with os.Stat
package core
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
"path/filepath"
)
var TemplateRoot string
var templateCache map[string]cachedTemplate
type cachedTemplate struct {
*template.Template
os.FileInfo
}
func readTemplateFile(abspath string) (*template.Template, error) {
relpath, err := filepath.Rel(TemplateRoot, abspath)
if err != nil {
return nil, fmt.Errorf(`core: unable to resolve template file path %v`, abspath)
}
t, err := template.ParseFiles(abspath)
if err != nil {
return nil, fmt.Errorf(`core: unable to read template file at path %v: %v`, abspath, err)
}
fi, err := os.Stat(abspath)
if err != nil {
return nil, fmt.Errorf(`core: unable to stat (2) template at path %v: %v`, abspath, err)
}
templateCache[relpath] = cachedTemplate{t, fi}
return t, nil
}
func Template(relpath string) (*template.Template, error) {
abspath := filepath.Join(TemplateRoot, relpath)
if cached, ok := templateCache[relpath]; ok {
fi, err := os.Stat(abspath)
if err != nil {
return nil, fmt.Errorf(`core: unable to stat template at path %v: %v`, abspath, err)
}
if fi.ModTime().After(cached.ModTime()) {
return readTemplateFile(abspath)
}
return cached.Template, nil
}
return readTemplateFile(abspath)
}
func init() {
templateCache = make(map[string]cachedTemplate, 5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment