profile.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package profile
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "github.com/spf13/viper"
  8. "github.com/usememos/memos/server/version"
  9. )
  10. // Profile is the configuration to start main server.
  11. type Profile struct {
  12. // Mode can be "prod" or "dev" or "demo"
  13. Mode string `json:"mode"`
  14. // Port is the binding port for server
  15. Port int `json:"-"`
  16. // Data is the data directory
  17. Data string `json:"-"`
  18. // DSN points to where Memos stores its own data
  19. DSN string `json:"-"`
  20. // Version is the current version of server
  21. Version string `json:"version"`
  22. }
  23. func (p *Profile) IsDev() bool {
  24. return p.Mode != "prod"
  25. }
  26. func checkDSN(dataDir string) (string, error) {
  27. // Convert to absolute path if relative path is supplied.
  28. if !filepath.IsAbs(dataDir) {
  29. absDir, err := filepath.Abs(filepath.Dir(os.Args[0]) + "/" + dataDir)
  30. if err != nil {
  31. return "", err
  32. }
  33. dataDir = absDir
  34. }
  35. // Trim trailing / in case user supplies
  36. dataDir = strings.TrimRight(dataDir, "/")
  37. if _, err := os.Stat(dataDir); err != nil {
  38. return "", fmt.Errorf("unable to access data folder %s, err %w", dataDir, err)
  39. }
  40. return dataDir, nil
  41. }
  42. // GetProfile will return a profile for dev or prod.
  43. func GetProfile() (*Profile, error) {
  44. profile := Profile{}
  45. err := viper.Unmarshal(&profile)
  46. if err != nil {
  47. return nil, err
  48. }
  49. if profile.Mode != "demo" && profile.Mode != "dev" && profile.Mode != "prod" {
  50. profile.Mode = "demo"
  51. }
  52. if profile.Mode == "prod" && profile.Data == "" {
  53. profile.Data = "/var/opt/memos"
  54. }
  55. dataDir, err := checkDSN(profile.Data)
  56. if err != nil {
  57. fmt.Printf("Failed to check dsn: %s, err: %+v\n", dataDir, err)
  58. return nil, err
  59. }
  60. profile.Data = dataDir
  61. profile.DSN = fmt.Sprintf("%s/memos_%s.db", dataDir, profile.Mode)
  62. profile.Version = version.GetCurrentVersion(profile.Mode)
  63. return &profile, nil
  64. }