pages.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package webpages
  2. import (
  3. "embed"
  4. _ "embed"
  5. "fmt"
  6. "io"
  7. "io/fs"
  8. "log"
  9. "os"
  10. "path"
  11. "git.aetherial.dev/aeth/keiji/pkg/env"
  12. )
  13. //go:embed html cdn
  14. var content embed.FS
  15. type ServiceOption string
  16. const EMBED ServiceOption = "embed"
  17. const FILESYSTEM ServiceOption = "filesystem"
  18. /*
  19. Creates the new filesystem implementer for serving the webpages to the API
  20. :param opt: the service option to
  21. */
  22. func NewContentLayer(opt ServiceOption) fs.FS {
  23. if opt == EMBED {
  24. fmt.Println("Using embed files to pull html templates")
  25. return content
  26. }
  27. if opt == FILESYSTEM {
  28. fmt.Println("Using filesystem to pull html templates")
  29. return FilesystemWebpages{Webroot: path.Base(os.Getenv(env.WEB_ROOT))}
  30. }
  31. log.Fatal("Unknown option was passed: ", opt)
  32. return content
  33. }
  34. type WebContentLayer interface{}
  35. type EmbeddedWebpages struct{}
  36. type FilesystemWebpages struct {
  37. Webroot string
  38. }
  39. /*
  40. Implementing the io.FS interface for interoperability
  41. */
  42. func (f FilesystemWebpages) Open(file string) (fs.File, error) {
  43. filePath := path.Join(f.Webroot, file)
  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, os.ErrNotExist
  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. }