pages.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. fmt.Println(filePath)
  44. fh, err := os.Open(filePath)
  45. if err != nil {
  46. fmt.Printf("Error opening the file: %s because %s", filePath, err)
  47. return nil, err
  48. }
  49. return fh, nil
  50. }
  51. /*
  52. Read content to a string for easy template ingestion. Will panic if the underlying os.Open call fails
  53. */
  54. func ReadToString(rdr fs.FS, name string) string {
  55. fh, err := rdr.Open(name)
  56. if err != nil {
  57. log.Fatal(err, "couldnt open the file: ", name)
  58. }
  59. b, err := io.ReadAll(fh)
  60. if err != nil {
  61. log.Fatal("Could not read the file: ", name)
  62. }
  63. return string(b)
  64. }