pages.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package webpages
  2. import (
  3. "embed"
  4. _ "embed"
  5. "fmt"
  6. "io"
  7. "io/fs"
  8. "log"
  9. "os"
  10. "path"
  11. )
  12. //go:embed html cdn
  13. var content embed.FS
  14. type ServiceOption string
  15. const EMBED ServiceOption = "embed"
  16. const FILESYSTEM ServiceOption = "filesystem"
  17. /*
  18. Creates the new filesystem implementer for serving the webpages to the API
  19. :param opt: the service option to
  20. */
  21. func NewContentLayer(opt ServiceOption) fs.FS {
  22. if opt == EMBED {
  23. fmt.Println("Using embed files to pull html templates")
  24. return content
  25. }
  26. if opt == FILESYSTEM {
  27. fmt.Println("Using filesystem to pull html templates")
  28. return FilesystemWebpages{Webroot: path.Base(os.Getenv("WEB_ROOT"))}
  29. }
  30. log.Fatal("Unknown option was passed: ", opt)
  31. return content
  32. }
  33. type WebContentLayer interface{}
  34. type EmbeddedWebpages struct{}
  35. type FilesystemWebpages struct {
  36. Webroot string
  37. }
  38. /*
  39. Implementing the io.FS interface for interoperability
  40. */
  41. func (f FilesystemWebpages) Open(file string) (fs.File, error) {
  42. filePath := path.Join(os.Getenv("WEB_ROOT"), file)
  43. fh, err := os.Open(filePath)
  44. if err != nil {
  45. fmt.Printf("Error opening the file: %s because %s", filePath, err)
  46. return nil, err
  47. }
  48. return fh, nil
  49. }
  50. /*
  51. Read content to a string for easy template ingestion. Will panic if the underlying os.Open call fails
  52. */
  53. func ReadToString(rdr fs.FS, name string) string {
  54. fh, err := rdr.Open(name)
  55. if err != nil {
  56. log.Fatal(err, "couldnt open the file: ", name)
  57. }
  58. b, err := io.ReadAll(fh)
  59. if err != nil {
  60. log.Fatal("Could not read the file: ", name)
  61. }
  62. return string(b)
  63. }