config

package
v0.19.765 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

README

confg

Nuon's opinionated approach to service configuration.

Usage

By default, we have a config.go file in each service's internal directory. This config outlines the service's custom configuration and usually embeds either workflows/worker/config.go (worfklow worker) or config.Base from this package.

Defaults

We consider defaults bad practice, and we should generally avoid them. Instead, set values for local in the services service.yml file.

When you need to define a default config, do so in the init function, as follows:

func init() {
    config.RegisterDefault("default_key", "default_value")
}

type Config struct {
    config.Base        `config:",squash"`
    GraphqlApiToken    string `config:"graphql_api_token"`
    ApiToken           string `config:"api_token"`
    RedisAddress       string `config:"redis_address"`
    MaxJobsInFlight    int    `config:"max_jobs_in_flight"`
    AwsSecretAccessKey string `config:"aws_secret_access_key"`
    AwsAccessKeyId     string `config:"aws_access_key_id"`
}

To load the config in your service:

func exec(cmd *cobra.Command, args []string) {
    var cfg Config
    if err := config.LoadInto(cmd.Flags(), &cfg); err != nil {
        log.Fatal("failed to load config", err.Error())
    }

    fmt.Printf("%#v", cfg)
}

The library takes order of operations from Env -> Config file (json|yaml) -> cli flags you can use the default config.yml|json and set the values there or set environment variables that match the config: struct tags uppercased

Documentation

Index

Constants

View Source
const (
	// ConfigTagName is the name of the field tag to use for config values
	ConfigTagName = "config"
	// TagValueSquash is the tag value used when squashing embedded structs
	TagValueSquash = ",squash"
)

Variables

View Source
var Version string = "unknown"

Version is set by ldflags, do not set / use this directly use the value exposed from the Base config

Functions

func LoadInto

func LoadInto(flags *pflag.FlagSet, to interface{}) error

LoadInto load the configuration into the supplied struct using the standard Loader

func RegisterDefault

func RegisterDefault(key string, value interface{})

RegisterDefault registers a default value for a configuration key

func RegisterDefaults

func RegisterDefaults(kvs map[string]interface{})

RegisterDefaults register the set of default key/value pairs

func SetEnvPrefix

func SetEnvPrefix(prefix string)

SetEnvPrefix sets the prefix to env vars that are searched

Types

type Base

type Base struct {
	Env                          Env     `config:"env"`
	LogLevel                     string  `config:"log_level"`
	ExportRuntimeMetrics         bool    `config:"export_runtime_metrics"`
	ProjectID                    string  `config:"project_id"`
	ServiceOwner                 string  `config:"service_owner"`
	ServiceName                  string  `config:"service_name"`
	SystemPort                   int     `config:"system_port"`
	TraceAddress                 string  `config:"host_ip"`
	TraceMaxBatchCount           int     `config:"trace_max_batch_count"`
	TraceSampleRate              float64 `config:"trace_sample_rate"`
	ProfilerEnabled              bool    `config:"profiler_enabled"`
	ProfilerBlockProfileRate     int     `config:"profiler_block_profile_rate"`
	ProfilerMutexProfileFraction int     `config:"profiler_mutex_profile_fraction"`
	DisableLogSampling           bool    `config:"disable_log_sampling"`
	DisableStackTraces           bool    `config:"disable_stack_traces"`
	Version                      string  `config:"version"`
}

Base is the base configuration for all services

type Config

type Config interface {
	Get(key string) interface{}
	GetBool(key string) bool
	GetFloat64(key string) float64
	GetInt(key string) int
	GetInt32(key string) int32
	GetInt64(key string) int64
	GetUint(key string) uint
	GetUint32(key string) uint32
	GetUint64(key string) uint64
	GetString(key string) string
	GetStringMap(key string) map[string]interface{}
	GetStringMapString(key string) map[string]string
	GetStringSlice(key string) []string
	GetTime(key string) time.Time
	GetDuration(key string) time.Duration
	IsSet(key string) bool
	Set(key string, value interface{})
	Bind(to interface{}) error
	Debug()
	SetSecure(key string)
	WriteTo(w io.Writer) (int64, error)
}

Config provides access to application configuration information

func Load

func Load(flags *pflag.FlagSet) (Config, error)

Load load the configuration using the standard Loader

type Env

type Env string

Env is an environment string

const (
	// Production is the production environment
	Production Env = "production"
	// Development is a development environment not local
	Development Env = "development"
	// Stage is a staging environment
	Stage Env = "stage"
)

func (*Env) String

func (e *Env) String() string

func (*Env) UnmarshalConfig

func (e *Env) UnmarshalConfig(value string)

UnmarshalConfig unmarshals a config value string to the associated interface type

type Loader

type Loader interface {
	RegisterDefault(key string, value interface{})
	RegisterDefaults(kvs map[string]interface{})
	SetEnvPrefix(string)
	Load(flags *pflag.FlagSet) (Config, error)
	LoadInto(flags *pflag.FlagSet, to interface{}) error
	LoadedConfig() Config
}

Loader loads configurations from multiple sources

func NewFileLoader

func NewFileLoader(file string) Loader

NewFileLoader creates a new config Loader instance with the supplied config file

func NewLoader

func NewLoader(paths ...string) Loader

NewLoader creates a new config Loader instance

type Option

type Option func(*options)

Option is a configuration option for the metrics system

func WithHTTPServer

func WithHTTPServer(httpServer *http.Server) Option

WithHTTPServer passes the http.Server to bind to

type Unmarshaler

type Unmarshaler interface {
	UnmarshalConfig(value string)
}

Unmarshaler describes a custom Unmarshal function that can be used to bind config values

Jump to

Keyboard shortcuts

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