platform.go 1.7 KB

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