profile.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package profile
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "os"
  6. "path/filepath"
  7. "runtime"
  8. "strings"
  9. "github.com/pkg/errors"
  10. )
  11. // Profile is the configuration to start main server.
  12. type Profile struct {
  13. // Mode can be "prod" or "dev" or "demo"
  14. Mode string
  15. // Addr is the binding address for server
  16. Addr string
  17. // Port is the binding port for server
  18. Port int
  19. // Data is the data directory
  20. Data string
  21. // DSN points to where memos stores its own data
  22. DSN string
  23. // Driver is the database driver
  24. // sqlite, mysql
  25. Driver string
  26. // Version is the current version of server
  27. Version string
  28. // InstanceURL is the url of your memos instance.
  29. InstanceURL string
  30. }
  31. func (p *Profile) IsDev() bool {
  32. return p.Mode != "prod"
  33. }
  34. func checkDataDir(dataDir string) (string, error) {
  35. // Convert to absolute path if relative path is supplied.
  36. if !filepath.IsAbs(dataDir) {
  37. relativeDir := filepath.Join(filepath.Dir(os.Args[0]), dataDir)
  38. absDir, err := filepath.Abs(relativeDir)
  39. if err != nil {
  40. return "", err
  41. }
  42. dataDir = absDir
  43. }
  44. // Trim trailing \ or / in case user supplies
  45. dataDir = strings.TrimRight(dataDir, "\\/")
  46. if _, err := os.Stat(dataDir); err != nil {
  47. return "", errors.Wrapf(err, "unable to access data folder %s", dataDir)
  48. }
  49. return dataDir, nil
  50. }
  51. func (p *Profile) Validate() error {
  52. if p.Mode != "demo" && p.Mode != "dev" && p.Mode != "prod" {
  53. p.Mode = "demo"
  54. }
  55. if p.Mode == "prod" && p.Data == "" {
  56. if runtime.GOOS == "windows" {
  57. p.Data = filepath.Join(os.Getenv("ProgramData"), "memos")
  58. if _, err := os.Stat(p.Data); os.IsNotExist(err) {
  59. if err := os.MkdirAll(p.Data, 0770); err != nil {
  60. slog.Error("failed to create data directory", slog.String("data", p.Data), slog.String("error", err.Error()))
  61. return err
  62. }
  63. }
  64. } else {
  65. p.Data = "/var/opt/memos"
  66. }
  67. }
  68. dataDir, err := checkDataDir(p.Data)
  69. if err != nil {
  70. slog.Error("failed to check dsn", slog.String("data", dataDir), slog.String("error", err.Error()))
  71. return err
  72. }
  73. p.Data = dataDir
  74. if p.Driver == "sqlite" && p.DSN == "" {
  75. dbFile := fmt.Sprintf("memos_%s.db", p.Mode)
  76. p.DSN = filepath.Join(dataDir, dbFile)
  77. }
  78. return nil
  79. }