A simple multi-layered config loader for Go. Made for smaller projects. No external dependencies.

gocfg

⚠️ Work in progress!

A simple multi-layered config loader for Go.

Made for smaller projects. No external dependencies.

Example

From main.go:

// Define your configuration struct:
type Config struct {
	RepoOwner   string
	RepoName    string
	URL         string
	HTTPTimeout time.Duration
}

// A config is complete when it can be validated.
// By optionally implementing the Config interface's Validate, we can detect errors.
func (c *Config) Validate() error {
	var errors config.Errors
	if !strings.HasPrefix(c.URL, "http") {
		// Capture errors on a per-field basis by naming the errors accordingly.
		// This way, the config loader knows which fields are valid.
		errors.Add(config.Err("URL", c.URL, "must be a valid URL (starting with http)"))
	}
	if c.HTTPTimeout < 1*time.Second {
		errors.Add(config.Err("HTTPTimeout", c.HTTPTimeout, "must be >= 1s"))
	}
	return errors.AsError() // returns nil if we did not add any error
}

// Config providers follow below signature and return a config and eventually an error.
// There is nothing that prevents the config from being a provider for itself:
func (c *Config) Config() (interface{}, error) {
	return c, c.Validate() // makes some things easier later on
}

// Name the config provider accordingly to make it easily identifiable later on.
func (c *Config) Name() string {
	return "Static"
}

func main() {
	// get config from 'JSON' first, fallback to 'Static' defaults otherwise:
	loader := config.From(provider.JSON("config.json")).
		WithDefaults(&Config{
			RepoOwner: "kdevo",
			RepoName:  "gocfg",
		}) // works because we've implemented the config provider interface above
	var cfg Config
	err := loader.Resolve(&cfg) // calls Validate if implemented
	if err != nil {
		// examine errors by providers to find out the cause:
		fmt.Printf("providers errors: %v\n", loader.ProviderErrors())
	}
	fmt.Printf("got config: %v\n", cfg)
}

Please also take a look at the config loader test.

Loading Rules

  1. Earlier config providers take precedence.
  2. Config structs must be marshable.
  3. Empty/ommitted fields are skipped.
  4. Fields with errors are skipped (see below).

Provider Errors

  1. Returning config.Errors with the specified field names will skip the field.
  2. Field names must follow rules of encoding/json.
  3. Returning regular errors will skip the entire provider (e.g. if the config is corrupt).

Tips:

  1. Skip fields that couldn't be provided by using config.Errors (e.g. when a value has an invalid format).
  2. Use descriptive field names that are unlikely to change.
  3. Return a regular error if we can't provide anything (e.g. Unmarshal error for JSON provider).
Owner
Kai Dinghofer
Passionate Software Engineer
Kai Dinghofer
Similar Resources

Injective's Oracle with dynamic price feeds (for External Integrations)

Injective's Oracle with dynamic price feeds. Allows anyone to start their own pre-approved price submission process to the oracle module on the Injective Chain.

Aug 29, 2022

Poc rsa - A simple golang scaffolding to help me to create new api projects or workers with golang on k8s

go-scaffold A simple golang scaffolding to help me to create new api projects or

Feb 3, 2022

The example shows how to build a simple multi-tier web application using Kubernetes and Docker

The example shows how to build a simple multi-tier web application using Kubernetes and Docker

Guestbook Example This example shows how to build a simple multi-tier web application using Kubernetes and Docker. The application consists of a web f

Nov 15, 2021

simple cloud made in GO

 simple cloud made in GO

simple cloud made in GO im doing this for fun and practice its a really simple cloud and its finished but the frontend its a little bit shitty.If you

Jun 19, 2022

A simple program to automatically backup a database using git. Err handling by Sentry, Reporting by Betteruptime. Made with 🩸 , 😓 & 😭

backup What is this? A Simple program to automatically backup a database using git. Err handling by Sentry, Uses heartbeats by Betteruptime Made with

Nov 4, 2022

Collect data about your dependencies

Collect data about your dependencies Features and Data Sources: Go modules, runs tests, detects tests and benchmarks Flexible rendering with Graphviz,

Dec 20, 2022

A lightweight Vault client module written in Go, with no dependencies, that is intuitive and user-friendly

libvault A lightweight Hashicorp Vault client written in Go, with no dependencies. It aims to provide an intuitive, simple API that is easy to use. Ju

Sep 18, 2022

Terraform Controller manages the life cycles of a terraform resource, allowing developers to self-serve dependencies in a controlled manner.

Terraform Controller manages the life cycles of a terraform resource, allowing developers to self-serve dependencies in a controlled manner.

TERRAFORM CONTROLLER Terraform Controller manages the life cycles of a terraform resource, allowing developers to self-serve dependencies in a control

Dec 15, 2022

Envoy file based dynamic routing using kubernetes config map

Envoy File Based Dynamic Routing Config mapを使用してEnvoy File Based Dynamic Routingを実現します。 概要 アーキテクチャとしては、 +----------+ +--------------+ +-----------

Dec 30, 2022
Related tags
AWS environment config loader

awsenv AWS environment config loader. awsenv is a small binary that loads AWS environment variables for an AWS profile from ~/.aws/credentials - usefu

Nov 28, 2022
Manage Go Versions/Projects/Dependencies
Manage Go Versions/Projects/Dependencies

rodent rodent is a shell (bash) application which: Manages multiple versions of Go. Allows you to test/build your projects against multiple Go release

Dec 13, 2022
Clones github projects into ~/Projects/github/{org}/{repo}

Tidy clone Github cli extension (gh extension) to clone repos into ~/Projects/github/{org}/{repo} on the local filesystem Install gh extension install

Jan 19, 2022
Open, Multi-Cloud, Multi-Cluster Kubernetes Orchestration
Open, Multi-Cloud, Multi-Cluster Kubernetes Orchestration

Karmada Karmada: Open, Multi-Cloud, Multi-Cluster Kubernetes Orchestration Karmada (Kubernetes Armada) is a Kubernetes management system that enables

Dec 30, 2022
Go WhatsApp Multi-Device Implementation in REST API with Multi-Session/Account Support

Go WhatsApp Multi-Device Implementation in REST API This repository contains example of implementation go.mau.fi/whatsmeow package with Multi-Session/

Dec 3, 2022
kubetnl tunnels TCP connections from within a Kubernetes cluster to a cluster-external endpoint, e.g. to your local machine. (the perfect complement to kubectl port-forward)

kubetnl kubetnl (kube tunnel) is a command line utility to tunnel TCP connections from within a Kubernetes to a cluster-external endpoint, e.g. to you

Dec 16, 2022
Traefik-redirect-operator is created to substitute manual effort of creating an ingress and service type External.
Traefik-redirect-operator is created to substitute manual effort of creating an ingress and service type External.

Overview Traefik Redirect Operator is used to help creating a combination of Ingress of Traefik controller along with Service's ExternalName type. The

Sep 22, 2021
Use cli tool to troubleshoot external API service quickly.
Use cli tool to troubleshoot external API service quickly.

golang CLI Template golang project template for building CLI Setup Setup by Command git clone https://github.com/mpppk/cli-template your_awesome_tool

Jan 5, 2022
Using this you can access node external ip address value from your pod.

Using this you can access node external ip address value from your pod.

Jan 30, 2022
Injective-price-oracle-ext - Injective's Oracle with dynamic price feeds (for External Integrations)

injective-price-oracle Injective's Oracle with dynamic price feeds. Allows anyon

Aug 29, 2022