config

package module
v1.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 24, 2023 License: Apache-2.0 Imports: 15 Imported by: 0

README

Config

Go go.mod Go version Go Report Card Go Reference

The config package provides functionality for loading and processing configuration values from environment variables and command line flags. It offers support for custom decoders, parsers, and mutators.

To install the config package, use the following command:

go get github.com/farrukhny/config

Usage

Tags

The config package uses struct tags to specify configuration options. Here are the available tags:

  • env: Specifies the environment variable name for the field.
  • default: Specifies the default value for the field.
  • required: Specifies whether the field is required. Default value can not be used if the field is required.
  • usage: Specifies the description of the field.
  • flag: Specifies the command line flag name for the field.
  • shortFlag: Specifies the short command line flag name for the field.
  • mask: Specifies whether the field value should be masked in the output.
Defining Configuration Struct

First, define a struct that represents your application's configuration settings. You can use struct tags to specify environment variable names, default values, and more.

type AppConfig struct {
    Port     int    `env:"APP_PORT" default:"8080" usage:"Port number"`
    LogLevel string `env:"LOG_LEVEL" default:"info" usage:"Log level"`
    // ... other configuration fields
}
Loading Configuration

Load the configuration using the config.Process function. It will read environment variables and command-line flags, applying any specified mutators.

Basic Usage:
func Process(cfg interface{}, mutator ...MutatorFunc) error
func main() {
    var cfg AppConfig
    err := config.Process(&cfg)
    if err != nil {
        // Handle error
    }

    // Your application logic using cfg
}
Using Parsers

You can also use custom parsers to load configuration from different sources, such as files or remote services. Create parsers that implement the config.Parser interface.

type Parser interface {
    Parse(cfg interface{}) error
}
type FileParser struct {
    FilePath string
}

func (p *FileParser) Parse(cfg interface{}) error {
    // Read configuration from file and populate cfg
    return nil
}

Then, use the config.ProcessWithParser function:

func ProcessWithParser(cfg interface{}, parsers []Parser, mutator ...MutatorFunc) error
func main() {
    var cfg AppConfig
    err := config.ProcessWithParser(&cfg, []config.Parser{&FileParser{FilePath: "config.json"}})
    if err != nil {
        // Handle error
    }

    // Your application logic using cfg
}
Custom Decoders

The Decoder interface declares the Decode method, which can be implemented to provide custom decoding logic.

type Decoder interface {
    Decode(val string) error
}
Example Usage
import (
    "encoding/base64"
)

type Base64Decoder struct{}

func (d *Base64Decoder) Decode(val string) error {
    decoded, err := base64.StdEncoding.DecodeString(val)
    if err != nil {
        return err
    }
    
    // Use the decoded value
    // e.g., return the decoded value or set it to a field

    return nil
}

Mutator Functions

The MutatorFunc is a function type that mutates a value of a key before it is set to the field. for example, pulling secrets from a secret manager and setting them to the configuration struct.

type MutatorFunc func(key, value string) (string, error)
Example Usage
func secretMutator(key, value string) (string, error) {
// Retrieve secret using the key and any necessary logic
secretValue, err := retrieveSecretFromManager(key)
    if err != nil {
        return "", err
    }
    return secretValue, nil
}

Documentation

Overview

Package config provides functionality for loading and processing configuration values from environment variables and command line flags. It offers support for custom decoders, parsers, and mutators.

To install the config package, use the following command:

go get github.com/farrukhny/config

Usage:

 Tags:

 The config package uses struct tags to specify configuration options. Here are the available tags:

   - env: Specifies the environment variable name for the field.
   - default: Specifies the default value for the field.
   - required: Specifies whether the field is required. Default value can not be used if the field is required.
   - usage: Specifies the description of the field.
   - flag: Specifies the command line flag name for the field.
   - shortFlag: Specifies the short command line flag name for the field.
   - mask: Specifies whether the field value should be masked in the output.

 Defining Configuration Struct:

 First, define a struct that represents your application's configuration settings. You can use struct tags to specify environment variable names, default values, and more.

	type AppConfig struct {
	    Port     int    `env:"APP_PORT" default:"8080" usage:"Port number"`
	    LogLevel string `env:"LOG_LEVEL" default:"info" usage:"Log level"`
	    // ... other configuration fields
	}

 Loading Configuration:

 Load the configuration using the config.Process function. It will read environment variables and command-line flags, applying any specified mutators.

 Basic Usage:

	func Process(cfg interface{}, mutator ...MutatorFunc) error

	func main() {
	    var cfg AppConfig
	    err := config.Process(&cfg)
	    if err != nil {
	        // Handle error
	    }
	    // Your application logic using cfg
	}

 Using Parsers:

 You can also use custom parsers to load configuration from different sources, such as files or remote services. Create parsers that implement the config.Parser interface.

	type Parser interface {
	    Parse(cfg interface{}) error
	}

	type FileParser struct {
	    FilePath string
	}

	func (p *FileParser) Parse(cfg interface{}) error {
	    // Read configuration from file and populate cfg
	    return nil
	}

 Then, use the config.ProcessWithParser function:

	func ProcessWithParser(cfg interface{}, parsers []Parser, mutator ...MutatorFunc) error

	func main() {
	    var cfg AppConfig
	    err := config.ProcessWithParser(&cfg, []config.Parser{&FileParser{FilePath: "config.json"}})
	    if err != nil {
	        // Handle error
	    }
	    // Your application logic using cfg
	}

 Custom Decoders:

 The Decoder interface declares the Decode method, which can be implemented to provide custom decoding logic.

	type Decoder interface {
	    Decode(val string) error
	}

 Example Usage:

	import (
	    "encoding/base64"
	)

	type Base64Decoder struct{}

	func (d *Base64Decoder) Decode(val string) error {
	    decoded, err := base64.StdEncoding.DecodeString(val)
	    if err != nil {
	        return err
	    }
	    // Use the decoded value
	    // e.g., return the decoded value or set it to a field
	    return nil
	}

 Mutator Functions:

 The MutatorFunc is a function type that mutates a value of a key before it is set to the field.
 For example, pulling secrets from a secret manager and setting them to the configuration struct.

	type MutatorFunc func(key, value string) (string, error)

 Example Usage:

	func secretMutator(key, value string) (string, error) {
	    // Retrieve secret using the key and any necessary logic
	    secretValue, err := retrieveSecretFromManager(key)
	    if err != nil {
	        return "", err
	    }
	    return secretValue, nil
	}

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrHelp is returned when the help flag is set.
	ErrHelp = errors.New("help requested")
	// ErrVersion is returned when the version flag is set.
	ErrVersion = errors.New("version requested")
)
View Source
var (
	ErrInvalidTarget = errors.New("targetStruct must be a non-nil pointer")
)

Functions

func JSONStartupMessage

func JSONStartupMessage(cfg interface{}) (string, error)

JSONStartupMessage generates the startup message in JSON format.

func Process

func Process(cfg interface{}, mutator ...MutatorFunc) error

Process processes the struct with environment variables and command line flags source. It also accepts mutator function to mutate the value before it is set to the field.

func ProcessWithParser

func ProcessWithParser(cfg interface{}, parsers []Parser, mutator ...MutatorFunc) error

ProcessWithParser processes the struct with the given parsers. After processing with the parsers it will process the struct with environment variables and command line flags source. It also accepts mutator function to mutate the value before it is set to the field.

func StartupMessage

func StartupMessage(cfg interface{}) (string, error)

StartupMessage generates the startup message.

func UsageMessage

func UsageMessage(cfg interface{}) (string, error)

UsageMessage generates the usage message.

Types

type Base64Bytes

type Base64Bytes []byte

Base64Bytes is a type that can be used to decode base64 encoded

func (*Base64Bytes) Bytes

func (b *Base64Bytes) Bytes() []byte

Bytes returns the underlying byte slice.

func (*Base64Bytes) Decode

func (b *Base64Bytes) Decode(val string) error

Decode implements the Decoder interface.

type Decoder

type Decoder interface {
	Decode(val string) error
}

Decoder is the interface that wraps the Decode method. Can be used to implement custom decoders.

type Field

type Field struct {
	FieldValue reflect.Value
	Name       string
	EnvVar     string
	Flag       string
	ShortFlag  rune
	Default    string
	Required   bool
	Mask       bool
	Usage      string
}

type HexBytes

type HexBytes []byte

HexBytes is a type that can be used to decode hex encoded

func (*HexBytes) Bytes

func (h *HexBytes) Bytes() []byte

Bytes returns the underlying byte slice.

func (*HexBytes) Decode

func (h *HexBytes) Decode(val string) error

Decode implements the Decoder interface.

type MutatorFunc

type MutatorFunc func(key, value string) (string, error)

MutatorFunc is a function that mutates a value of the key before it is set to the field.

type Parser

type Parser interface {
	Parse(cfg interface{}) error
}

Parser declare behavior to extend the different parsers that can be used to unmarshal config.

type Version

type Version struct {
	// Major version number
	Major int

	// Minor version number
	Minor int

	// Patch Number
	Patch int

	// PreRelease is the pre-release version
	PreRelease string

	// CommitHash git commit the build is based on
	CommitHash string

	// Branch the build is based on
	Branch string

	// Metadata is the build metadata
	Metadata string

	// BuildNumber is the build number
	BuildNumber int

	// BuildTime is the time the application was built.
	BuildTime time.Time
}

Version variables are set at build time.

func NewVersion

func NewVersion(major, minor, patch int, preRelease, commitHash, branch, metadata string, buildNumber int) Version

NewVersion returns a new Version struct

func (Version) Version

func (v Version) Version() string

Version is the current version of the application.

func (Version) VersionInfo

func (v Version) VersionInfo() string

VersionInfo provides output to display the application version with more details like commit hash, branch, build time and metadata. it is displayed in the following format: <version> <commit hash> <branch> <build time> <metadata>

Directories

Path Synopsis
Package yaml provides yaml support by implementing the Parser interface.
Package yaml provides yaml support by implementing the Parser interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL