Skip to content

cinar/config2

Repository files navigation

GoDoc License Build Status

Config2 Go

Config2 is a lightweight Golang module for managing and populating application configuration from JSON, command line, and environment variables.

Usage

Install package.

go get github.com/cinar/config2

Import Config2.

import (
  "github.com/cinar/config2
)

Define a configuration structure as shown below.

type Config struct {
	Host  string `usage:"Server hostname"`
	Port  int    `usage:"Server port"`
	Debug bool   `usage:"Enable debug"`
}

Config2 provides the following field tags to define additional information for configuration variables.

Tag Description Example
usage Usage for command line help. `usage:"Server hostname"

Set the default values for the configuration variables.

config := &Config{Port: 8080}

Read from command line arguments

Config2 can automatically generate a FlagSet for your configuration structure and parse the command line arguments.

Application can be launched with command line arguments.

./main -Debug -Host localhost -Port 9090

Use the ParseCommandLine function to parse the command line arguments as shown below.

flagSet := config2.ParseCommandLine(os.Args, config)

Validate the configuration variables. In case of an error, show the usage through the returned FlagSet as shown below.

flagSet.PrintDefaults()

The command line arguments, their usage, and their defaults will be shown by the FlagSet as usual.

  -Debug
        Enable debug (default false)
  -Host
        Server hostname
  -Port
        Server port (default 8080)

Read from environment variables

Config2 can read configuration from the environment variables.

Application can be launched with the environment variables set as shown below.

export test_Host=localhost
export test_Port=9090
export test_Debug=true

./main

Use the ParseEnvironmentVariables function to parse the environment variables. The function takes a prefix for the environment variables. Please set it to empty string ("") if no prefix is needed.

config2.ParseEnvironmentVariables("test_", config)

Read from JSON file

Config2 can read configuration from a JSON file as well, such as the one below.

{
  "Host": "localhost",
  "Port": 9090,
  "Debug": true
}

Use the ParseJson function to parse the JSON file.

err := config2.ParseJson("test.json", config)
if err != nil {
  log.Fatal(err)
}

Parse all

Config2 can parse the JSON file if it exists, parse the environment variables, and parse the command line arguments.

Use the ParseAll function as shown below.

config2.ParseAll("test.json", "test_", config)

License

The source code is provided under MIT License.

About

Config2 is a lightweight Golang module for managing and populating application configuration from JSON, command line, and env variables.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages