gocfg

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2024 License: MIT Imports: 3 Imported by: 1

README

Go Configuration Library

This project is a Go library for reading configuration data from various sources such as environment variables, command-line flags, and configuration files. The library provides a unified interface for reading configuration data, making it easier to manage and maintain your application's configuration.

Attention

The library uses the env, pflag, yaml, toml and godotenv codebase to work with environment variables and flags. This is a temporary solution, maybe I’ll write my own implementation later. Thanks to the authors of these libraries for the work done!

Installation

To install the library, use the go get command:

go get github.com/dsbasko/go-cfg

Usage

The library provides several functions for reading configuration data:

  • ReadEnv(cfg any) error: Reads environment variables into the provided cfg structure. Each field in the cfg structure represents an environment variable.
  • MustReadEnv(cfg any): Similar to ReadEnv but panics if the reading process fails.
  • ReadFlag(cfg any) error: Reads command-line flags into the provided cfg structure. Each field in the cfg structure represents a command-line flag.
  • MustReadFlag(cfg any): Similar to ReadFlag but panics if the reading process fails.
  • ReadFile(path string, cfg any) error: Reads configuration from a file into the provided cfg structure. The path parameter is the path to the configuration file. Each field in the cfg structure represents a configuration option. Supported file formats include JSON, YAML, TOML and .env.
  • MustReadFile(path string, cfg any): Similar to ReadFile but panics if the reading process fails.

Here is an example of how to use the library:

package main

import (
	"github.com/dsbasko/go-cfg"
)

type Config struct {
	Mode string `default:"prod" json:"mode" yaml:"mode" s-flag:"m" flag:"mode" env:"MODE" description:"mode of the application (dev|prod)"`
	HTTP struct {
		Host         string `default:"localhost" json:"host" yaml:"host" s-flag:"h" flag:"http-host" env:"HTTP_HOST"`
		Port         int    `default:"3000" json:"port" yaml:"port" s-flag:"p" flag:"http-port" env:"HTTP_PORT"`
		ReadTimeout  int    `json:"read_timeout" yaml:"read-timeout" flag:"http-read-timeout" env:"HTTP_READ_TIMEOUT"`
		WriteTimeout int    `json:"write_timeout" yaml:"write-timeout" flag:"http-write-timeout" env:"HTTP_WRITE_TIMEOUT"`
	} `json:"http" yaml:"http"`
}

func main() {
	cfg := Config{}

	gocfg.MustReadFile("configs/config.yaml", &cfg)
	gocfg.MustReadEnv(&cfg)
	gocfg.MustReadFlag(&cfg)
}

Note that you can configure the priority of the configuration. For example, you can first read YAML configs, then environment variables, and finally flags, or vice versa.

Flags

Run a project with flags: go run ./cmd/main.go -s="some short flag" --flat=f1 --nested n1

type config struct {
	WithShort string `s-flag:"s" flag:"with-short" description:"With short flag"`
	Flat      string `flag:"flat" description:"Flat flag"`
	Parent    struct {
		Nested string `flag:"nested" description:"Nested flag"`
	}
}

func main() {
	var cfg config
	if err := gocfg.ReadFlag(&cfg); err != nil {
		log.Panicf("failed to read flag: %v", err)
	}
	// or: gocfg.MustReadFlag(&cfg)

	log.Printf("WithShort: %v\n", cfg.WithShort)
	log.Printf("Flat: %v\n", cfg.Flat)
	log.Printf("Nested: %v\n", cfg.Parent.Nested)
}

// WithShort: some short flag
// Flat: f1
// Nested: n1

Struct tags are available for working with flags:

  • default default value;
  • flag the name of the flag;
  • s-flag short name of the flask (1 symbol);
  • description description of the flag that is displayed when running the --help command.

Environment variables

The env structure tag is used for environment variables. Run a project with environment variables: FLAT=f1 NESTED=n1 go run ./cmd/main.go

type config struct {
	Flat   string `env:"FLAT"`
	Parent struct {
		Nested string `env:"NESTED"`
	}
}

func main() {
	var cfg config
	if err := gocfg.ReadEnv(&cfg); err != nil {
		log.Panicf("failed to read env: %v", err)
	}
	// or: gocfg.MustReadEnv(&cfg)

	log.Printf("Flat: %v\n", cfg.Flat)
	log.Printf("Nested: %v\n", cfg.Parent.Nested)
}

// Flat: f1
// Nested: n1

Struct tags are available for working with environment variables:

  • default default value;
  • env the name of the environment variable.

Files

Run a project with environment variables: go run ./cmd/main.go

type config struct {
	Flat   string `yaml:"flat"`
	Parent struct {
		Nested string `yaml:"nested"`
	}
}

func main() {
	var cfg config
	if err := gocfg.ReadFile(path.Join("cmd", "config.yaml"), &cfg); err != nil {
		log.Panicf("failed to read config.yaml file: %v", err)
	}
	// or: gocfg.MustReadFile(path.Join("cmd", "config.yaml"), &cfg)

	log.Printf("Flat: %v\n", cfg.Flat)
	log.Printf("Nested: %v\n", cfg.Parent.Nested)
}

// Flat: f1
// Nested: n1

Structure of the yaml file:

flat: f1
foo:
  nested: n1

Struct tags are available for working with environment variables:

  • default default value;
  • env for files of the format .env
  • yaml for files of the format .yaml or .yml
  • toml for files of the format .toml
  • json for files of the format .json


If you enjoyed this project, I would appreciate it if you could give it a star! If you notice any problems or have any suggestions for improvement, please feel free to create a new issue. Your feedback means a lot to me!

❤️ Dmitriy Basenko

Documentation

Overview

Package gocfg is a Go library for reading configuration data from various sources. It provides a unified interface for reading configuration data from environment variables, command-line flags, and configuration files.

Installation

To install the library, use the go get command:

go get github.com/dsbasko/go-cfg

Usage

The library provides several functions for reading configuration data:

ReadEnv(cfg any) error
    Reads environment variables into the provided cfg structure. Each field in the cfg structure represents an environment variable.

MustReadEnv(cfg any)
    Similar to ReadEnv but panics if the reading process fails.

ReadFlag(cfg any) error
    Reads command-line flags into the provided cfg structure. Each field in the cfg structure represents a command-line flag.

MustReadFlag(cfg any)
    Similar to ReadFlag but panics if the reading process fails.

ReadFile(path string, cfg any) error
    Reads configuration from a file into the provided cfg structure. The path parameter is the path to the configuration file. Each field in the cfg structure represents a configuration option. Supported file formats include JSON and YAML.

MustReadFile(path string, cfg any)
    Similar to ReadFile but panics if the reading process fails.

Here is an example of how to use the library:

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MustReadEnv

func MustReadEnv(cfg any)

MustReadEnv is similar to ReadEnv but panics if the reading process fails. This function is useful when the absence of environment variables should lead to a program termination.

Example:

type Config struct {
	Mode string `env:"MODE"`
	HTTP struct {
		Host string `env:"HTTP_HOST"`
		Port int    `env:"HTTP_PORT"`
	}
}

func main() {
	cfg := &Config{}
	gocfg.MustReadEnv(cfg)

	fmt.Printf("Mode: %s\n", cfg.Mode)
	fmt.Printf("HTTP Host: %s\n", cfg.HTTP.Host)
	fmt.Printf("HTTP Port: %d\n", cfg.HTTP.Port)
}

This will read the MODE, HTTP_HOST and HTTP_PORT environment variables into the Mode, HTTP.Host and HTTP.Port fields of the cfg variable. If any of these environment variables are not set, the program will panic.

func MustReadFile

func MustReadFile(path string, cfg any)

MustReadFile is similar to ReadFile but panics if the reading process fails. This function is useful when the absence of a configuration file should lead to a program termination.

Example:

type Config struct {
	Mode string `yaml:"mode"`
	HTTP struct {
		Host string `yaml:"host"`
		Port int    `yaml:"port"`
	} `yaml:"http"`
}

func main() {
	cfg := &Config{}
	gocfg.MustReadFile("config.yaml", cfg)

	fmt.Printf("Mode: %s\n", cfg.Mode)
	fmt.Printf("HTTP Host: %s\n", cfg.HTTP.Host)
	fmt.Printf("HTTP Port: %d\n", cfg.HTTP.Port)
}

This will read the mode, http_host and http_port configuration options from the config.yaml file into the Mode, HTTP.Host and HTTP.Port fields of the cfg variable. If any of these configuration options are not set in the file, the program will panic.

func MustReadFlag

func MustReadFlag(cfg any)

MustReadFlag is similar to ReadFlag but panics if the reading process fails. This function is useful when the absence of command-line flags should lead to a program termination.

Example:

type Config struct {
	Mode string `flag:"mode" s-flag:"m" description:"Application mode"`
	HTTP struct {
		Host string `flag:"http-host" s-flag:"hh" description:"HTTP host"`
		Port int    `flag:"http-port" s-flag:"hp" description:"HTTP port"`
	}
}

func main() {
	cfg := &Config{}
	gocfg.MustReadFlag(cfg)

	fmt.Printf("Mode: %s\n", cfg.Mode)
	fmt.Printf("HTTP Host: %s\n", cfg.HTTP.Host)
	fmt.Printf("HTTP Port: %d\n", cfg.HTTP.Port)
}

This will read the command-line flags --mode, --http-host and --http-port (or -m, -hh and -hp respectively) into the Mode, HTTP.Host and HTTP.Port fields of the cfg variable. If any of these flags are not set, the program will panic.

func ReadEnv

func ReadEnv(cfg any) error

ReadEnv is a function that reads environment variables into the provided cfg structure. The cfg parameter should be a pointer to a struct where each field represents an environment variable. The function returns an error if the reading process fails.

Example of how to use the ReadEnv function:

Define a struct that represents your environment variables. For example:

type Config struct {
	Mode string `env:"MODE"`
	HTTP struct {
		Host string `env:"HTTP_HOST"`
		Port int    `env:"HTTP_PORT"`
	}
}

Then, create an instance of your struct and call the ReadEnv function:

func main() {
	cfg := &Config{}
	if err := gocfg.ReadEnv(cfg); err != nil {
		log.Fatalf("failed to read environment variables: %v", err)
	}

	fmt.Printf("Mode: %s\n", cfg.Mode)
	fmt.Printf("HTTP Host: %s\n", cfg.HTTP.Host)
	fmt.Printf("HTTP Port: %d\n", cfg.HTTP.Port)
}

This will read the MODE, REST_HOST and REST_PORT environment variables into the Mode, HTTP.Host and HTTP.Port fields of the cfg variable.

func ReadFile

func ReadFile(path string, cfg any) error

ReadFile reads configuration from a file into the provided cfg structure. The path parameter is the path to the configuration file. The cfg parameter should be a pointer to a struct where each field represents a configuration option. This function returns an error if the reading process fails.

Example:

type Config struct {
	Mode string `yaml:"mode"`
	HTTP struct {
		Host string `yaml:"http_host"`
		Port int    `yaml:"http_port"`
	}
}

func main() {
	cfg := &Config{}
	if err := gocfg.ReadFile("config.yaml", cfg); err != nil {
		log.Fatalf("failed to read configuration file: %v", err)
	}

	fmt.Printf("Mode: %s\n", cfg.Mode)
	fmt.Printf("HTTP Host: %s\n", cfg.HTTP.Host)
	fmt.Printf("HTTP Port: %d\n", cfg.HTTP.Port)
}

This will read the mode, http_host and http_port configuration options from the config.yaml file into the Mode, HTTP.Host and HTTP.Port fields of the cfg variable. If any of these configuration options are not set in the file, the function will return an error.

func ReadFlag

func ReadFlag(cfg any) error

ReadFlag reads command-line flags into the provided cfg structure. The cfg parameter should be a pointer to a struct where each field represents a command-line flag. This function returns an error if the parsing process fails.

Example:

type Config struct {
	Mode string `flag:"mode" s-flag:"m" description:"Application mode"`
	HTTP struct {
		Host string `flag:"http-host" s-flag:"hh" description:"HTTP host"`
		Port int    `flag:"http-port" s-flag:"hp" description:"HTTP port"`
	}
}

func main() {
	cfg := &Config{}
	if err := gocfg.ReadFlag(cfg); err != nil {
		log.Fatalf("failed to read command-line flags: %v", err)
	}

	fmt.Printf("Mode: %s\n", cfg.Mode)
	fmt.Printf("HTTP Host: %s\n", cfg.HTTP.Host)
	fmt.Printf("HTTP Port: %d\n", cfg.HTTP.Port)
}

This will read the command-line flags --mode, --http-host and --http-port (or -m, -hh and -hp respectively) into the Mode, HTTP.Host and HTTP.Port fields of the cfg variable. If any of these flags are not set, the function will return an error.

Types

This section is empty.

Directories

Path Synopsis
internal
env

Jump to

Keyboard shortcuts

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