memos/server/profile/profile.go

78 lines
1.6 KiB
Go
Raw Normal View History

2022-05-22 09:29:34 +08:00
package profile
2022-02-05 13:04:06 +08:00
import (
"fmt"
"os"
"path/filepath"
2022-02-18 22:21:10 +08:00
"strconv"
2022-02-05 13:04:06 +08:00
"strings"
2022-06-27 22:09:06 +08:00
"github.com/usememos/memos/common"
2022-02-05 13:04:06 +08:00
)
2022-05-22 09:29:34 +08:00
// Profile is the configuration to start main server.
2022-02-05 13:04:06 +08:00
type Profile struct {
2022-05-02 09:40:25 +08:00
// Mode can be "prod" or "dev"
2022-03-29 20:53:43 +08:00
Mode string `json:"mode"`
2022-05-17 21:21:13 +08:00
// Port is the binding port for server
2022-03-29 20:53:43 +08:00
Port int `json:"port"`
// DSN points to where Memos stores its own data
2022-05-01 11:06:29 +08:00
DSN string `json:"dsn"`
2022-05-17 21:21:13 +08:00
// Version is the current version of server
Version string `json:"version"`
2022-02-05 13:04:06 +08:00
}
func checkDSN(dataDir string) (string, error) {
// Convert to absolute path if relative path is supplied.
if !filepath.IsAbs(dataDir) {
absDir, err := filepath.Abs(filepath.Dir(os.Args[0]) + "/" + dataDir)
if err != nil {
return "", err
}
dataDir = absDir
}
// Trim trailing / in case user supplies
dataDir = strings.TrimRight(dataDir, "/")
if _, err := os.Stat(dataDir); err != nil {
2022-02-06 10:37:09 +08:00
error := fmt.Errorf("unable to access -data %s, err %w", dataDir, err)
2022-02-05 13:04:06 +08:00
return "", error
}
return dataDir, nil
}
// GetDevProfile will return a profile for dev.
2022-05-17 21:21:13 +08:00
func GetProfile() *Profile {
2022-02-18 22:21:10 +08:00
mode := os.Getenv("mode")
2022-05-02 09:40:25 +08:00
if mode != "dev" && mode != "prod" {
2022-02-18 22:21:10 +08:00
mode = "dev"
}
port, err := strconv.Atoi(os.Getenv("port"))
if err != nil {
port = 8080
}
2022-05-01 11:06:29 +08:00
data := ""
2022-05-02 09:40:25 +08:00
if mode == "prod" {
2022-05-01 11:06:29 +08:00
data = "/var/opt/memos"
}
2022-02-05 13:04:06 +08:00
2022-02-18 22:21:10 +08:00
dataDir, err := checkDSN(data)
2022-02-05 13:04:06 +08:00
if err != nil {
2022-02-06 10:37:09 +08:00
fmt.Printf("Failed to check dsn: %s, err: %+v\n", dataDir, err)
2022-02-05 13:04:06 +08:00
os.Exit(1)
}
2022-05-01 11:06:29 +08:00
dsn := fmt.Sprintf("%s/memos_%s.db", dataDir, mode)
2022-02-05 13:04:06 +08:00
2022-05-17 21:21:13 +08:00
return &Profile{
Mode: mode,
Port: port,
DSN: dsn,
2022-05-22 09:29:34 +08:00
Version: common.Version,
2022-02-05 13:04:06 +08:00
}
}