env.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package env
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "github.com/joho/godotenv"
  7. )
  8. const IMAGE_STORE = "IMAGE_STORE"
  9. const WEB_ROOT = "WEB_ROOT"
  10. const DOMAIN_NAME = "DOMAIN_NAME"
  11. const HOST_PORT = "HOST_PORT"
  12. const HOST_ADDR = "HOST_ADDR"
  13. const SSL_MODE = "SSL_MODE"
  14. const CHAIN = "CHAIN"
  15. const KEY = "KEY"
  16. var OPTION_VARS = map[string]string{
  17. IMAGE_STORE: "#the location for keiji to store the images uploaded (string)",
  18. WEB_ROOT: "#the location to pull HTML and various web assets from. Only if using 'keiji -content fs' (string)",
  19. CHAIN: "#the path to the SSL public key chain (string)",
  20. KEY: "#the path to the SSL private key (string)",
  21. }
  22. var REQUIRED_VARS = map[string]string{
  23. HOST_PORT: "#the port to run the server on (int)",
  24. HOST_ADDR: "#the address for the server to listen on (string)",
  25. DOMAIN_NAME: "#the servers domain name, i.e. 'aetherial.dev', or 'localhost' (string)",
  26. SSL_MODE: "#chose to use SSL or not (boolean)",
  27. }
  28. type EnvNotSet struct {
  29. NotSet string
  30. }
  31. func (e *EnvNotSet) Error() string {
  32. return fmt.Sprintf("Environment variable: '%s' was not set.", e.NotSet)
  33. }
  34. /*
  35. Write out a blank .env configuration with the the required configuration (uncommented) and the
  36. optional configuration (commented out)
  37. :param path: the path to write the template to
  38. */
  39. func WriteTemplate(path string) {
  40. var out string
  41. out = out + "####### Required Configuration #######\n"
  42. for k, v := range REQUIRED_VARS {
  43. out = out + fmt.Sprintf("%s\n%s=\n", v, k)
  44. }
  45. out = out + "\n####### Optional Configuration #######\n"
  46. for k, v := range OPTION_VARS {
  47. out = out + fmt.Sprintf("# %s\n# %s=\n", v, k)
  48. }
  49. err := os.WriteFile(path, []byte(out), os.ModePerm)
  50. if err != nil {
  51. log.Fatal("Failed to write file: ", err)
  52. }
  53. }
  54. /*
  55. verify all environment vars passed in are set
  56. :param vars: array of strings to verify
  57. */
  58. func LoadAndVerifyEnv(path string, vars map[string]string) error {
  59. err := godotenv.Load(path)
  60. if err != nil {
  61. return err
  62. }
  63. for i := range vars {
  64. if os.Getenv(vars[i]) == "" {
  65. return &EnvNotSet{NotSet: vars[i]}
  66. }
  67. }
  68. return nil
  69. }