github.com/v2fly/v2ray-core/v4@v4.45.2/common/platform/platform.go (about) 1 package platform 2 3 import ( 4 "os" 5 "path/filepath" 6 "strconv" 7 "strings" 8 ) 9 10 type EnvFlag struct { 11 Name string 12 AltName string 13 } 14 15 func NewEnvFlag(name string) EnvFlag { 16 return EnvFlag{ 17 Name: name, 18 AltName: NormalizeEnvName(name), 19 } 20 } 21 22 func (f EnvFlag) GetValue(defaultValue func() string) string { 23 if v, found := os.LookupEnv(f.Name); found { 24 return v 25 } 26 if len(f.AltName) > 0 { 27 if v, found := os.LookupEnv(f.AltName); found { 28 return v 29 } 30 } 31 32 return defaultValue() 33 } 34 35 func (f EnvFlag) GetValueAsInt(defaultValue int) int { 36 useDefaultValue := false 37 s := f.GetValue(func() string { 38 useDefaultValue = true 39 return "" 40 }) 41 if useDefaultValue { 42 return defaultValue 43 } 44 v, err := strconv.ParseInt(s, 10, 32) 45 if err != nil { 46 return defaultValue 47 } 48 return int(v) 49 } 50 51 func NormalizeEnvName(name string) string { 52 return strings.ReplaceAll(strings.ToUpper(strings.TrimSpace(name)), ".", "_") 53 } 54 55 func getExecutableDir() string { 56 exec, err := os.Executable() 57 if err != nil { 58 return "" 59 } 60 return filepath.Dir(exec) 61 } 62 63 func getExecutableSubDir(dir string) func() string { 64 return func() string { 65 return filepath.Join(getExecutableDir(), dir) 66 } 67 } 68 69 func GetPluginDirectory() string { 70 const name = "v2ray.location.plugin" 71 pluginDir := NewEnvFlag(name).GetValue(getExecutableSubDir("plugins")) 72 return pluginDir 73 } 74 75 func GetConfigurationPath() string { 76 const name = "v2ray.location.config" 77 configPath := NewEnvFlag(name).GetValue(getExecutableDir) 78 return filepath.Join(configPath, "config.json") 79 } 80 81 // GetConfDirPath reads "v2ray.location.confdir" 82 func GetConfDirPath() string { 83 const name = "v2ray.location.confdir" 84 configPath := NewEnvFlag(name).GetValue(func() string { return "" }) 85 return configPath 86 }