conf

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2024 License: Apache-2.0 Imports: 9 Imported by: 0

README

Conf

Simple configuration package for Go applications. It is easy to use and this package support only environment variables (for 12-Factor apps).

Install

go get github.com/virp/conf

Usage Example

package main

import (
	"fmt"
	"log"

	"github.com/virp/conf"
)

type RedisConfig struct {
	Addr     string `conf:"required"`
	Password string
	DB       int `conf:"default:0"`
}

type AWS struct {
	Key    string `conf:"required,env:AWS_ACCESS_KEY_ID"`
	Secret string `conf:"required,env:AWS_SECRET_ACCESS_KEY"`
	Region string `conf:"default:eu-central-1,env:AWS_DEFAULT_REGION"`
}

type Config struct {
	Debug bool
	Redis RedisConfig
	AWS   AWS
}

func main() {
	var cfg Config
	if err := conf.Parse("my_service", &cfg); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Debug: %t\n", cfg.Debug) // MY_SERVICE_DEBUG
	fmt.Printf(
		"Redis:\n\tAddr: %s\n\tPassword: %s\n\tDB: %d\n",
		cfg.Redis.Addr,     // MY_SERVICE_REDIS_ADDR
		cfg.Redis.Password, // MY_SERVICE_REDIS_PASSWORD
		cfg.Redis.DB,       // MY_SERVICE_REDIS_DB
	)
	fmt.Printf(
		"AWS\n\tKey: %s\n\tSecret: %s\n\tRegion: %s\n",
		cfg.AWS.Key,    // AWS_ACCESS_KEY_ID or MY_SERVICE_AWS_ACCESS_KEY_ID
		cfg.AWS.Secret, // AWS_SECRET_ACCESS_KEY or MY_SERVICE_AWS_SECRET_ACCESS_KEY
		cfg.AWS.Region, // AWS_DEFAULT_REGION or MY_SERVICE_AWS_DEFAULT_REGION
	)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidStruct = errors.New("configuration must be a struct pointer")

Functions

func Parse

func Parse(prefix string, cfg any) error

Parse parses the specified config struct. This function will apply the defaults first and then apply environment variables to the struct.

Types

type Field

type Field struct {
	Name    string
	EnvKey  string
	Field   reflect.Value
	Options FieldOptions
}

Field maintains information about a field in the configuration struct.

type FieldError

type FieldError struct {
	// contains filtered or unexported fields
}

A FieldError occurs when an error occurs updating an individual field in the provided struct value.

func (*FieldError) Error

func (err *FieldError) Error() string

type FieldOptions

type FieldOptions struct {
	DefaultVal string
	EnvName    string
	Required   bool
}

FieldOptions maintain flag options for a given field.

type Setter

type Setter interface {
	Set(value string) error
}

Setter is implemented by types can self-deserialize values.

Jump to

Keyboard shortcuts

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