1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-27 14:26:11 -04:00

get asset location on demand

This commit is contained in:
Darien Raymond 2017-11-06 12:23:21 +01:00
parent 064d7249f5
commit 482793d28a
2 changed files with 30 additions and 17 deletions

View File

@ -12,7 +12,7 @@ type EnvFlag struct {
AltName string
}
func (f EnvFlag) GetValue(defaultValue string) string {
func (f EnvFlag) GetValue(defaultValue func() string) string {
if v, found := os.LookupEnv(f.Name); found {
return v
}
@ -22,13 +22,16 @@ func (f EnvFlag) GetValue(defaultValue string) string {
}
}
return defaultValue
return defaultValue()
}
func (f EnvFlag) GetValueAsInt(defaultValue int) int {
const PlaceHolder = "xxxxxx"
s := f.GetValue(PlaceHolder)
if s == PlaceHolder {
useDefaultValue := false
s := f.GetValue(func() string {
useDefaultValue = true
return ""
})
if useDefaultValue {
return defaultValue
}
v, err := strconv.ParseInt(s, 10, 32)
@ -42,18 +45,13 @@ func NormalizeEnvName(name string) string {
return strings.Replace(strings.ToUpper(strings.TrimSpace(name)), ".", "_", -1)
}
var assetPath = "/"
func init() {
defAssetLocation, err := os.Executable()
if err == nil {
defAssetLocation = filepath.Dir(defAssetLocation)
assetPath = (EnvFlag{
Name: "v2ray.location.asset",
}).GetValue(defAssetLocation)
}
}
func GetAssetLocation(file string) string {
assetPath := EnvFlag{Name: "v2ray.location.asset"}.GetValue(func() string {
exec, err := os.Executable()
if err != nil {
return ""
}
return filepath.Dir(exec)
})
return filepath.Join(assetPath, file)
}

View File

@ -1,6 +1,8 @@
package platform_test
import (
"os"
"path/filepath"
"testing"
. "v2ray.com/core/common/platform"
@ -39,3 +41,16 @@ func TestEnvFlag(t *testing.T) {
Name: "xxxxx.y",
}.GetValueAsInt(10), Equals, 10)
}
func TestGetAssetLocation(t *testing.T) {
assert := With(t)
exec, err := os.Executable()
assert(err, IsNil)
loc := GetAssetLocation("t")
assert(filepath.Dir(loc), Equals, filepath.Dir(exec))
os.Setenv("v2ray.location.asset", "/v2ray")
assert(GetAssetLocation("t"), Equals, "/v2ray/t")
}