gitee.com/h79/goutils@v1.22.10/common/config/config.go (about)

     1  package config
     2  
     3  import (
     4  	"context"
     5  	"flag"
     6  	"fmt"
     7  	"gitee.com/h79/goutils/common/file"
     8  	"os"
     9  	"os/exec"
    10  	"path/filepath"
    11  	"runtime"
    12  	"strings"
    13  )
    14  
    15  const (
    16  	EProd = "prod"
    17  	ETest = "test"
    18  	EDev  = "dev"
    19  )
    20  
    21  const (
    22  	KForever  = "forever"
    23  	KDaemon   = "daemon"
    24  	KPprof    = "pprof"
    25  	KPath     = "path"
    26  	KEnv      = "env"
    27  	KConf     = "conf"
    28  	KDataPath = "dataPath"
    29  	KAppId    = "appid"
    30  )
    31  
    32  var (
    33  	Version  = "1.0.0"
    34  	AppName  = "unknown"
    35  	AppAlias = "" //别名,example 某某公司的某某应用
    36  	AppId    string
    37  	SeqId    int64 = 0
    38  	Source   string
    39  	Env      = EDev
    40  	WorkDir  string
    41  	MainConf string
    42  	DataPath string //程序存储数据
    43  	Daemon   bool
    44  	Forever  bool
    45  	Pprof    bool
    46  )
    47  
    48  var (
    49  	appExecPath     string
    50  	envPath         string
    51  	confPath        string
    52  	appConfPath     string
    53  	appDataPath     string //程序运行数据目录,如views,docs
    54  	appDataPathV2   string
    55  	defaultDataPath string
    56  	appDataVersion  int //数据版本
    57  )
    58  
    59  type Config struct {
    60  	appDataPath    string //程序运行数据目录,如views,docs
    61  	appDataPathV2  string
    62  	appConfPath    string
    63  	workDir        string
    64  	dataPath       string
    65  	envPath        string
    66  	Mode           string `json:"mode" yaml:"mode" xml:"mode"`
    67  	Server         string `json:"server" yaml:"server" xml:"server"`
    68  	PubIP          string `json:"publicIp" yaml:"publicIp" xml:"publicIp"`
    69  	AppDataVersion int    `json:"appDataVersion" yaml:"appDataVersion" xml:"appDataVersion"`
    70  	EnabledRedis   bool   `json:"enabledRedis" yaml:"enabledRedis" xml:"enabledRedis"`
    71  	EnabledDb      bool   `json:"enabledDb" yaml:"enabledDb" xml:"enabledDb"`
    72  	EnabledEs      bool   `json:"enabledEs" yaml:"enabledEs" xml:"enabledEs"`
    73  	EnabledMQ      bool   `json:"enabledMQ" yaml:"enabledMQ" xml:"enabledMQ"`
    74  }
    75  
    76  type Option func(c *Config)
    77  
    78  func WithEnvPath(path string) Option {
    79  	return func(c *Config) {
    80  		c.envPath = path
    81  	}
    82  }
    83  func WithWorkDir(dir string) Option {
    84  	return func(c *Config) {
    85  		c.workDir = dir
    86  	}
    87  }
    88  
    89  func WithAppConfPath(p string) Option {
    90  	return func(c *Config) {
    91  		c.appConfPath = p
    92  	}
    93  }
    94  
    95  func WithAppDataPath(p string) Option {
    96  	return func(c *Config) {
    97  		c.appDataPath = p
    98  	}
    99  }
   100  
   101  func WithAppDataPathV2(p string) Option {
   102  	return func(c *Config) {
   103  		c.appDataPathV2 = p
   104  	}
   105  }
   106  
   107  func WithDataPath(p string) Option {
   108  	return func(c *Config) {
   109  		c.dataPath = p
   110  	}
   111  }
   112  
   113  func (c *Config) Init(opts ...Option) {
   114  	if len(Env) <= 0 {
   115  		Env = EDev
   116  	}
   117  	for i := range opts {
   118  		opts[i](c)
   119  	}
   120  	if c.workDir != "" {
   121  		WorkDir = c.workDir
   122  	}
   123  	if WorkDir == "." || WorkDir == "" {
   124  		if app := GetExecPath(); app != "" {
   125  			WorkDir = app
   126  		}
   127  	}
   128  	if !strings.HasSuffix(WorkDir, "/") {
   129  		WorkDir += "/"
   130  	}
   131  	WorkDir = filepath.Dir(WorkDir)
   132  
   133  	envPath = c.envPath
   134  	if envPath == "" || !file.IsExist(envPath) {
   135  		envPath = fmt.Sprintf("%s/env", WorkDir)
   136  	}
   137  	confPath = fmt.Sprintf("%s/conf", WorkDir)
   138  
   139  	if c.appConfPath == "" {
   140  		appConfPath = fmt.Sprintf("%s/%s", confPath, AppName)
   141  	} else {
   142  		appConfPath = c.appConfPath
   143  	}
   144  
   145  	if c.appDataPath == "" {
   146  		appDataPath = WorkDir
   147  	} else {
   148  		appDataPath = c.appDataPath
   149  	}
   150  
   151  	if c.appDataPathV2 == "" {
   152  		appDataPathV2 = fmt.Sprintf("%s/app", WorkDir)
   153  	} else {
   154  		appDataPathV2 = c.appDataPathV2
   155  	}
   156  
   157  	if MainConf == "" {
   158  		MainConf = fmt.Sprintf("%s/%s.main.json", appConfPath, Env)
   159  	}
   160  
   161  	defaultDataPath = fmt.Sprintf("%s/data/%s", WorkDir, AppName)
   162  	if DataPath == "" {
   163  		if c.dataPath != "" {
   164  			DataPath = c.dataPath
   165  		} else {
   166  			DataPath = defaultDataPath
   167  		}
   168  	}
   169  
   170  	Source = AppName
   171  }
   172  
   173  func init() {
   174  	var _ = AppAlias
   175  
   176  	flag.StringVar(&Env, KEnv, EDev, "dev,test,prod")
   177  	flag.StringVar(&WorkDir, KPath, ".", "path of work")
   178  	flag.StringVar(&MainConf, KConf, "", "config path of main.json")
   179  	flag.StringVar(&AppId, KAppId, "", "appid")
   180  	flag.StringVar(&DataPath, KDataPath, "", "data path")
   181  	flag.BoolVar(&Forever, KForever, false, "forever run")
   182  	flag.BoolVar(&Daemon, KDaemon, false, "daemon run")
   183  	flag.BoolVar(&Pprof, KPprof, false, "pprof switch")
   184  
   185  	flag.Usage = func() {
   186  		flag.PrintDefaults()
   187  	}
   188  }
   189  
   190  func IsProdEnvironment() bool {
   191  	return Env == EProd
   192  }
   193  
   194  func IsDevEnvironment() bool {
   195  	return Env == EDev
   196  }
   197  
   198  func IsTestEnvironment() bool {
   199  	return Env == ETest
   200  }
   201  
   202  // FileNameInEnvPath
   203  // env/{Env}/name
   204  func FileNameInEnvPath(name string) string {
   205  	return filepath.Join(envPath, Env, name)
   206  }
   207  
   208  // FileNameWithoutEnvInEnvPath
   209  // env/name
   210  func FileNameWithoutEnvInEnvPath(name string) string {
   211  	return filepath.Join(envPath, name)
   212  }
   213  
   214  // FileNameWithEnvInConfAppPath
   215  // conf/appName 带env "conf/{appName}/{Env}.name"
   216  func FileNameWithEnvInConfAppPath(name string) string {
   217  	return filepath.Join(appConfPath, WithEnv(name))
   218  }
   219  
   220  // FileNameWithoutEnvInConfAppPath
   221  // Deprecated: this function simply calls [FileNameInConfAppPath].
   222  func FileNameWithoutEnvInConfAppPath(name string) string {
   223  	return filepath.Join(appConfPath, name)
   224  }
   225  
   226  // FileNameInConfAppPath
   227  // conf/appName 不带env "conf/{appName}/name"
   228  func FileNameInConfAppPath(name string) string {
   229  	return filepath.Join(appConfPath, name)
   230  }
   231  
   232  // FileNameInConfPath
   233  // conf/ "confPath/name"
   234  func FileNameInConfPath(name string) string {
   235  	return filepath.Join(confPath, name)
   236  }
   237  
   238  // FileNameInAppDataPath
   239  // conf/ "{workdir}/name" 或 {workdir}/app/name
   240  func FileNameInAppDataPath(name string) string {
   241  	return filepath.Join(GetAppDataPath(), name)
   242  }
   243  
   244  // FileNameInAppDataPathV2
   245  // conf/ "{workdir}/app/name"
   246  func FileNameInAppDataPathV2(name string) string {
   247  	return filepath.Join(GetAppDataPathV2(), name)
   248  }
   249  
   250  // FileNameInDataPath
   251  // conf/ 目录下 "{DataPath}/name"
   252  func FileNameInDataPath(name string) string {
   253  	return filepath.Join(DataPath, name)
   254  }
   255  
   256  // FileNameWithEnvInDataPath
   257  // conf/ 目录下 "{DataPath}/{Env}.name"
   258  func FileNameWithEnvInDataPath(name string) string {
   259  	return filepath.Join(DataPath, WithEnv(name))
   260  }
   261  
   262  // FileNameInEnvDataPath
   263  // conf/ 目录下 "{DataPath}/{Env}/name"
   264  func FileNameInEnvDataPath(name string) string {
   265  	return filepath.Join(DataPath, Env, name)
   266  }
   267  
   268  // FileNameInWork
   269  // 工作目录下 "{WorkDir}/"
   270  func FileNameInWork(name string) string {
   271  	return filepath.Join(WorkDir, name)
   272  }
   273  
   274  // FileNameWithEnvInWork
   275  // 工作目录下 "{WorkDir}/"
   276  func FileNameWithEnvInWork(name string) string {
   277  	return filepath.Join(WorkDir, WithEnv(name))
   278  }
   279  
   280  // WithEnv
   281  // 与env组合
   282  func WithEnv(name string) string {
   283  	return fmt.Sprintf("%s.%s", Env, name)
   284  }
   285  
   286  // MainFileName env.main.json 全路径文件名
   287  func MainFileName() string {
   288  	return MainConf
   289  }
   290  
   291  // GetConfPath ./conf
   292  func GetConfPath() string {
   293  	return confPath
   294  }
   295  
   296  // GetConfAppPath ./conf/appName
   297  func GetConfAppPath() string {
   298  	return appConfPath
   299  }
   300  
   301  // GetDataPath 业务定义存储路径
   302  func GetDataPath() string {
   303  	return DataPath
   304  }
   305  
   306  func IsDefaultDataPath() bool {
   307  	return strings.EqualFold(DataPath, defaultDataPath)
   308  }
   309  
   310  // GetAppDataPath 程序运行数据目录,如views,docs
   311  func GetAppDataPath() string {
   312  	if appDataVersion >= 1 {
   313  		return GetAppDataPathV2()
   314  	}
   315  	return appDataPath
   316  }
   317  
   318  func GetAppDataPathV2() string {
   319  	return appDataPathV2
   320  }
   321  
   322  func GetEnvPath() string {
   323  	return envPath
   324  }
   325  
   326  func UseAppDataPathV2() {
   327  	UseAppDataVersion(1)
   328  	// to adjust
   329  	GetAppDataPath()
   330  }
   331  
   332  func UseAppDataVersion(ver int) {
   333  	appDataVersion = ver
   334  }
   335  
   336  func GetExecPath() string {
   337  	if len(appExecPath) > 0 {
   338  		return appExecPath
   339  	}
   340  	path, err := exec.LookPath(os.Args[0])
   341  	if err != nil {
   342  		return ""
   343  	}
   344  	appExecPath = filepath.Dir(path)
   345  	return appExecPath
   346  }
   347  
   348  func GetAppPath() (string, error) {
   349  	prog := os.Args[0]
   350  	p, err := filepath.Abs(prog)
   351  	if err != nil {
   352  		return "", err
   353  	}
   354  	fi, err := os.Stat(p)
   355  	if err == nil {
   356  		if !fi.Mode().IsDir() {
   357  			return p, nil
   358  		}
   359  		err = fmt.Errorf("GetAppPath: %s is directory", p)
   360  	}
   361  	if filepath.Ext(p) == "" && runtime.GOOS == "windows" {
   362  		p += ".exe"
   363  		fi, err = os.Stat(p)
   364  		if err == nil {
   365  			if !fi.Mode().IsDir() {
   366  				return p, nil
   367  			}
   368  			err = fmt.Errorf("GetAppPath: %s is directory", p)
   369  		}
   370  	}
   371  	return "", err
   372  }
   373  
   374  type HandlerFunc func(ctx context.Context, cmd int, configType, config string) (any, error)
   375  
   376  var RegisterConfig func(ty string, handler HandlerFunc)
   377  var UnRegisterConfig func(ty string)