Created
August 9, 2012 21:42
-
-
Save jordanorelli/3308291 to your computer and use it in GitHub Desktop.
primitive template cache in Go with os.Stat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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