profile.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package profile
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  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"
  13. Mode string `json:"mode"`
  14. // Port is the binding port for server
  15. Port int `json:"port"`
  16. // Data is the data directory
  17. Data string `json:"data"`
  18. // DSN points to where Memos stores its own data
  19. DSN string `json:"dsn"`
  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. flag.StringVar(&profile.Mode, "mode", "dev", "mode of server")
  43. flag.IntVar(&profile.Port, "port", 8081, "port of server")
  44. flag.StringVar(&profile.Data, "data", "", "data directory")
  45. flag.Parse()
  46. if profile.Mode != "dev" && profile.Mode != "prod" {
  47. profile.Mode = "dev"
  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. }