diff --git a/common/env.go b/common/env.go index 600e06f1..85b3681e 100644 --- a/common/env.go +++ b/common/env.go @@ -1,11 +1,19 @@ package common -type envKey string +type EnvKeyType string -// Env is a context key that can be used to set programmatically the environment +// EnvKey is a context key that can be used to set programmatically the environment // gopsutil relies on to perform calls against the OS. // Example of use: // -// ctx := context.WithValue(context.Background(), Env, map[string]string{"HOST_PROC": "/myproc"}) +// ctx := context.WithValue(context.Background(), common.EnvKey, EnvMap{"HOST_PROC": "/myproc"}) // avg, err := load.AvgWithContext(ctx) -var Env = envKey("env") +var EnvKey = EnvKeyType("env") + +const ( + HostProcEnvKey EnvKeyType = "HOST_PROC" + HostSysEnvKey EnvKeyType = "HOST_SYS" + HostEtcEnvKey EnvKeyType = "HOST_ETC" +) + +type EnvMap map[EnvKeyType]string diff --git a/internal/common/common.go b/internal/common/common.go index c5af6b5b..47d7897e 100644 --- a/internal/common/common.go +++ b/internal/common/common.go @@ -324,11 +324,11 @@ func PathExistsWithContents(filename string) bool { } // GetEnvWithContext retrieves the environment variable key. If it does not exist it returns the default. -// The context may optionally contain a map superseding os.Env. +// The context may optionally contain a map superseding os.EnvKey. func GetEnvWithContext(ctx context.Context, key string, dfault string, combineWith ...string) string { var value string - if env, ok := ctx.Value(common.Env).(map[string]string); ok { - value = env[key] + if env, ok := ctx.Value(common.EnvKey).(common.EnvMap); ok { + value = env[common.EnvKeyType(key)] } if value == "" { value = os.Getenv(key) diff --git a/internal/common/common_test.go b/internal/common/common_test.go index e216b18c..43638bf4 100644 --- a/internal/common/common_test.go +++ b/internal/common/common_test.go @@ -8,6 +8,8 @@ import ( "runtime" "strings" "testing" + + "github.com/shirou/gopsutil/v3/common" ) func TestReadlines(t *testing.T) { @@ -196,7 +198,7 @@ func TestGetEnvWithContextOverride(t *testing.T) { defer func() { os.Setenv("HOST_ETC", old) }() - ctx := context.WithValue(context.Background(), Env, map[string]string{"HOST_ETC": "/foo"}) + ctx := context.WithValue(context.Background(), common.EnvKey, common.EnvMap{common.HostEtcEnvKey: "/foo"}) p := HostEtcWithContext(ctx, "mtab") if p != "/foo/mtab" { t.Errorf("invalid HostEtc, %s", p)