goconfig

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2021 License: MIT Imports: 8 Imported by: 0

README

Release Build Status Report Go Mergify Status

goconfig

GoConfig provides strongly typed envrionment variable based configuration for go apps using a friendly Fluent API.

It comes with a viper implementation but others that implement the ConfigurationLoader interface can also be added.

Though it is billed as environment variable based, you can load configuration in however you wish, try to keep it 12 factor though with env vars.

Useage

Useage is very simple, at the start of your main first load your defaults, I tend to have a method like SetupDefaults that contains all the default settings for all environment variables in the application. Directly after this, call goconfig as shown:

func main(){
	config.SetupDefaults()
	cfg := goconfig.NewViperConfig("my-app").
		WithServer().
		WithDeployment().
		WithDb().
		Load()
}

With this simple syntax you can quickly glance at your main file and see the exact requirements for your application.

You can then reference configs directly rather than plucking them out of thin air throughput your code base.

For example, to get the server port do:

 svr := cfg.Server.Port

It is recommended that you use dependency injection rather than globals to pass these around, as such, they are all pointers.

 func NewImportantService(cfg *goconfig.Server){
	 cfg.Port
}

The above injection akes it 100% explicit as to the requirements of your service and is much easier tested than putting config readers throughout your code base.

Http Clients

We also support setup of custom http clients, this can be done as shown:

func main(){
	config.SetupDefaults()
	cfg := goconfig.NewViperConfig("my-app").
		WithServer().
		WithHTTPClient("my-service").
		WithHttpClient("my-other-service").
		Load()
}

Each of these gets its own config keyed off the service name as shown:

	EnvHTTPClientHost       = "%s.client.host"
	EnvHTTPClientPort       = "%s.client.port"
	...

In the case of my-service, it's environment config for host would be MY-SERVICE.CLIENT.HOST.

You can add as many as you need and can access them by calling svcCfg := cfg.CustomHTTPClient("my-service).

Contributing

Contributions are more than welcome, there is a limited set of configs available at present and I'll be adding them as I need them, so if you think you'd like to use this library but has something missing, like a Cassandra config, either raise an issue, create a PR adding it or both ideally.

Documentation

Index

Constants

View Source
const (
	EnvServerPort         = "server.port"
	EnvServerHost         = "server.host"
	EnvServerTLSEnabled   = "server.tls.enabled"
	EnvServerTLSCert      = "server.tls.cert"
	EnvServerPprofEnabled = "server.pprof.enabled"

	EnvSwaggerHost    = "swagger.host"
	EnvSwaggerEnabled = "swagger.enabled"

	EnvMetricsEnabled = "metrics.enabled"
	EnvTracingEnabled = "tracing.enabled"

	EnvEnvironment = "env.environment"
	EnvRegion      = "env.region"
	EnvVersion     = "env.version"
	EnvCommit      = "env.commit"
	EnvBuildDate   = "env.builddate"

	EnvLogLevel = "log.level"

	EnvDb        = "db.type"
	EnvDbSchema  = "db.schema.path"
	EnvDbDsn     = "db.dsn"
	EnvDbMigrate = "db.migrate"

	EnvHTTPClientHost       = "%s.client.host"
	EnvHTTPClientPort       = "%s.client.port"
	EnvHTTPClientTimeout    = "%s.client.timeout"
	EnvHTTPClientTLSEnabled = "%s.client.tls.enabled"
	EnvHTTPClientTLSCert    = "%s.client.tls.cert"

	EnvRedisAddress  = "redis.address"
	EnvRedisPassword = "redis.password"
	EnvRedisDb       = "redis.db"

	LogDebug = "debug"
	LogInfo  = "info"
	LogError = "error"
	LogWarn  = "warn"
)

Config keys used for goconfig, these get converted to UPPERCASE_SPLIT env vars.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Logging         *Logging
	Server          *Server
	Deployment      *Deployment
	Db              *Db
	Redis           *Redis
	Swagger         *Swagger
	Instrumentation *Instrumentation
	// contains filtered or unexported fields
}

Config returns strongly typed config values.

func (*Config) CustomHTTPClient

func (c *Config) CustomHTTPClient(name string) *HTTPClientConfig

CustomHTTPClient will return a custom http client, if not found nil is returned.

func (*Config) Validate

func (c *Config) Validate() error

Validate will check config values are valid and return a list of failures if any have been found.

type ConfigurationLoader

type ConfigurationLoader interface {
	WithServer() ConfigurationLoader
	WithEnvironment(appname string) ConfigurationLoader
	WithLog() ConfigurationLoader
	WithHTTPClient(name string) ConfigurationLoader
	WithDb() ConfigurationLoader
	WithRedis() ConfigurationLoader
	WithSwagger() ConfigurationLoader
	WithInstrumentation() ConfigurationLoader
	Load() *Config
}

ConfigurationLoader will load configuration items into a struct that contains a configuration.

type Db

type Db struct {
	Type       DbType
	SchemaPath string
	Dsn        string
	Migrate    bool
}

Db contains database information.

func (*Db) Validate

Validate will ensure the HeaderClient config is valid.

type DbType

type DbType string

DbType is used to restrict the dbs we can support.

const (
	DBSqlite   DbType = "sqlite"
	DBMySQL    DbType = "mysql"
	DBPostgres DbType = "postgres"
)

Supported database types.

type Deployment

type Deployment struct {
	Environment string
	AppName     string
	Region      string
	Version     string
	Commit      string
	BuildDate   time.Time
}

Deployment contains information relating to the current deployed instance.

func (*Deployment) IsDev

func (d *Deployment) IsDev() bool

IsDev determines if this app is running on a dev environment.

func (*Deployment) String

func (d *Deployment) String() string

String implements the stringer interface for printing.

type HTTPClientConfig

type HTTPClientConfig struct {
	Host       string
	Port       string
	TLSEnabled bool
	TLSCert    bool
	Timeout    time.Duration
}

HTTPClientConfig is a custom http client config struct, returned when CustomHTTPClient is called.

type Instrumentation

type Instrumentation struct {
	// MetricsEnabled will enable / disable metric collection such as prometheus.
	MetricsEnabled bool
	// TracingEnabled will enable / disable open tracing.
	TracingEnabled bool
}

Instrumentation contains metrics and tracing functionality.

type Logging

type Logging struct {
	Level string
}

Logging will set the default log level for the application.

type Redis

type Redis struct {
	Address  string
	Password string
	Db       uint
}

Redis config can be sued to connect to a redis instance usually for caching.

type Server

type Server struct {
	Port         string
	Hostname     string
	TLSCertPath  string
	TLSEnabled   bool
	PProfEnabled bool
}

Server contains all settings required to run a web server.

type Swagger

type Swagger struct {
	// Host, if set, will override the default swagger host which
	// is usually the same as the server hosting it ie 'localhost'.
	Host string
	// Enabled if true, can be used to switch swagger endpoints on.
	Enabled bool
}

Swagger contains swagger configuration.

type ViperConfig

type ViperConfig struct {
	*Config
}

ViperConfig wraps config and implements ConfigurationLoader.

func NewViperConfig

func NewViperConfig(appname string) *ViperConfig

NewViperConfig will setup and return viper configuration that implements goconfig.ConfigurationLoader.

func (*ViperConfig) Load

func (c *ViperConfig) Load() *Config

Load will finish setup and return configuration. This should always be the last call.

func (*ViperConfig) WithDb

func (c *ViperConfig) WithDb() ConfigurationLoader

WithDb sets up and returns database configuration.

func (*ViperConfig) WithEnvironment

func (c *ViperConfig) WithEnvironment(appName string) ConfigurationLoader

WithEnvironment sets up the deployment configuration if required.

func (*ViperConfig) WithHTTPClient

func (c *ViperConfig) WithHTTPClient(name string) ConfigurationLoader

WithHTTPClient will setup a custom http client referenced by name.

func (*ViperConfig) WithInstrumentation

func (c *ViperConfig) WithInstrumentation() ConfigurationLoader

WithInstrumentation will read instrumentation environment vars.

func (*ViperConfig) WithLog

func (c *ViperConfig) WithLog() ConfigurationLoader

WithLog sets up logger config from environment variables.

func (*ViperConfig) WithRedis

func (c *ViperConfig) WithRedis() ConfigurationLoader

WithRedis will include redis config.

func (*ViperConfig) WithServer

func (c *ViperConfig) WithServer() ConfigurationLoader

WithServer will setup the web server configuration if required.

func (*ViperConfig) WithSwagger

func (c *ViperConfig) WithSwagger() ConfigurationLoader

WithSwagger will setup and return swagger configuration.

Jump to

Keyboard shortcuts

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