profile.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 checkDSN(dataDir string) (string, error) {
  24. // Convert to absolute path if relative path is supplied.
  25. if !filepath.IsAbs(dataDir) {
  26. absDir, err := filepath.Abs(filepath.Dir(os.Args[0]) + "/" + dataDir)
  27. if err != nil {
  28. return "", err
  29. }
  30. dataDir = absDir
  31. }
  32. // Trim trailing / in case user supplies
  33. dataDir = strings.TrimRight(dataDir, "/")
  34. if _, err := os.Stat(dataDir); err != nil {
  35. return "", fmt.Errorf("unable to access data folder %s, err %w", dataDir, err)
  36. }
  37. return dataDir, nil
  38. }
  39. // GetDevProfile will return a profile for dev or prod.
  40. func GetProfile() (*Profile, error) {
  41. profile := Profile{}
  42. err := viper.Unmarshal(&profile)
  43. if err != nil {
  44. return nil, err
  45. }
  46. if profile.Mode != "demo" && profile.Mode != "dev" && profile.Mode != "prod" {
  47. profile.Mode = "demo"
  48. }
  49. if profile.Mode == "prod" && profile.Data == "" {
  50. profile.Data = "/var/opt/memos"
  51. }
  52. dataDir, err := checkDSN(profile.Data)
  53. if err != nil {
  54. fmt.Printf("Failed to check dsn: %s, err: %+v\n", dataDir, err)
  55. return nil, err
  56. }
  57. profile.Data = dataDir
  58. profile.DSN = fmt.Sprintf("%s/memos_%s.db", dataDir, profile.Mode)
  59. profile.Version = version.GetCurrentVersion(profile.Mode)
  60. return &profile, nil
  61. }