loader.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2016 José Santos <henrique_1609@me.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jet
  15. import (
  16. "io"
  17. "os"
  18. "path/filepath"
  19. )
  20. // Loader is a minimal interface required for loading templates.
  21. type Loader interface {
  22. // Exists checks for template existence.
  23. Exists(path string) (string, bool)
  24. // Open opens the underlying reader with template content.
  25. Open(path string) (io.ReadCloser, error)
  26. }
  27. // OSFileSystemLoader implements Loader interface using OS file system (os.File).
  28. type OSFileSystemLoader struct {
  29. dir string
  30. }
  31. // compile time check that we implement Loader
  32. var _ Loader = (*OSFileSystemLoader)(nil)
  33. // NewOSFileSystemLoader returns an initialized OSFileSystemLoader.
  34. func NewOSFileSystemLoader(dirPath string) *OSFileSystemLoader {
  35. return &OSFileSystemLoader{
  36. dir: dirPath,
  37. }
  38. }
  39. // Open opens a file from OS file system.
  40. func (l *OSFileSystemLoader) Open(path string) (io.ReadCloser, error) {
  41. return os.Open(filepath.Join(l.dir, path))
  42. }
  43. // Exists checks if the template name exists by walking the list of template paths
  44. // returns true if the template file was found
  45. func (l *OSFileSystemLoader) Exists(path string) (string, bool) {
  46. path = filepath.Join(l.dir, path)
  47. stat, err := os.Stat(path)
  48. if err == nil && !stat.IsDir() {
  49. return path, true
  50. }
  51. return "", false
  52. }