pages.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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
  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. return content
  24. }
  25. if opt == FILESYSTEM {
  26. fmt.Println(os.Getenv("WEB_ROOT"))
  27. return FilesystemWebpages{Webroot: path.Base(os.Getenv("WEB_ROOT"))}
  28. }
  29. log.Fatal("Unknown option was passed: ", opt)
  30. return content
  31. }
  32. type WebContentLayer interface{}
  33. type EmbeddedWebpages struct{}
  34. type FilesystemWebpages struct {
  35. Webroot string
  36. }
  37. /*
  38. Implementing the io.FS interface for interoperability
  39. */
  40. func (f FilesystemWebpages) Open(file string) (fs.File, error) {
  41. fmt.Println(path.Join(f.Webroot, file))
  42. return os.Open(path.Join(f.Webroot, file))
  43. }
  44. /*
  45. Read content to a string for easy template ingestion. Will panic if the underlying os.Open call fails
  46. */
  47. func ReadToString(rdr fs.FS, name string) string {
  48. fh, err := rdr.Open(name)
  49. if err != nil {
  50. log.Fatal(err, "couldnt open the file: ", name)
  51. }
  52. b, err := io.ReadAll(fh)
  53. if err != nil {
  54. log.Fatal("Could not read the file: ", name)
  55. }
  56. return string(b)
  57. }