go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/configutil/context.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package configutil
     9  
    10  import (
    11  	"context"
    12  )
    13  
    14  type configFilePathsKey struct{}
    15  
    16  // WithConfigPaths adds config file paths to the context.
    17  func WithConfigPaths(ctx context.Context, paths []string) context.Context {
    18  	return context.WithValue(ctx, configFilePathsKey{}, paths)
    19  }
    20  
    21  // GetConfigPaths gets the config file paths from a context.
    22  func GetConfigPaths(ctx context.Context) []string {
    23  	if raw := ctx.Value(configFilePathsKey{}); raw != nil {
    24  		if typed, ok := raw.([]string); ok {
    25  			return typed
    26  		}
    27  	}
    28  	return nil
    29  }
    30  
    31  type envVarsKey struct{}
    32  
    33  // WithEnvVars adds the env vars to the context.
    34  func WithEnvVars(ctx context.Context, vars map[string]string) context.Context {
    35  	return context.WithValue(ctx, envVarsKey{}, vars)
    36  }
    37  
    38  // GetEnvVars gets the env vars from a context.
    39  func GetEnvVars(ctx context.Context) map[string]string {
    40  	if raw := ctx.Value(envVarsKey{}); raw != nil {
    41  		if typed, ok := raw.(map[string]string); ok {
    42  			return typed
    43  		}
    44  	}
    45  	return parseEnv()
    46  }