xvals

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2021 License: Apache-2.0 Imports: 16 Imported by: 4

README

xvals

Introduction

xvals is a library for accessing external values. The library can be configured to read values from environment variables, config file and command line paramters.

It also contains an Object model, so that values grouped using a specific scheme can be treated as an object.

This initial use case for this was to unify the notion of Endpoints when dealing with multiple microservices. It facilitates the handling of these endpoints in regards of both dev ops and implementation.

Installation and usage

To install it, run:

go get github.com/staffano/xvals

License

The xvals package is licensed under the Apache License 2.0. Please see the LICENSE file for details.

Example

package main

import (
	"fmt"
	"os"

	"github.com/staffano/xvals"
	"gopkg.in/yaml.v3"
)

func main() {
	os.Setenv("EP_EP1_ADDRESS", "localhost:123")
	os.Setenv("EP_EP1_TLS", "mTLS")
	os.Setenv("EP_EP1_SERVER_CACERT", "ServerCACert")
	os.Setenv("EP_EP1_SERVER_CERT", "ServerCert")
	os.Setenv("EP_EP1_SERVER_KEY", "ServerKey")
	os.Setenv("EP_EP1_CLIENT_CACERT", "ClientCACert")
	os.Setenv("EP_EP1_CLIENT_CERT", "ClientCert")
	os.Setenv("EP_EP1_CLIENT_KEY", "ClientKey")
	os.Setenv("EP_EP1_PATH", "/this/is/a/path")

	xvals.WithEnvironment()
	xvals.WithObject(xvals.EndpointDescr)
	xvals.ReloadObjects()

	ep1, _ := xvals.GetObject(xvals.TpEndpoint, "ep1")

	d, _ := yaml.Marshal(ep1)
	fmt.Println(string(d))
}

Documentation

Index

Constants

View Source
const TpEndpoint = "EP"

TpEndpoint is the type name for an endpoint

Variables

View Source
var EndpointDescr = &epDescriptor{}

EndpointDescr contains the description of the endpoint

Functions

func BoolValue

func BoolValue(key string) (val bool, err error)

BoolValue is a convenience function to fetch and parse a value as a boolean

func BoolValueD added in v1.0.1

func BoolValueD(key string, defaultVal bool) bool

BoolValueD return values as bool, or return defaultVal, if it doesn't exist

func Dump

func Dump() map[string]string

Dump returns a merged set of all values available.

func FromKey

func FromKey(key string) (typ, name string)

FromKey parses the encoded type/name from the key

func HasValue

func HasValue(key string) bool

HasValue returns true if the value exist in the context

func IntValue

func IntValue(key string) (val int, err error)

IntValue is a convenience function to fetch and parse a value as an int

func IntValueD added in v1.0.1

func IntValueD(key string, defaultVal int) int

IntValueD return value as int, or defaultVal if non-existent.

func Key

func Key(typ, name string) string

Key returns the key based on type+name

func Objects

func Objects() map[string]Object

Objects returns the objects known to the store.

func ReloadObjects

func ReloadObjects()

ReloadObjects reloads objects based on the current external values

func Value

func Value(key string) (string, error)

Value returns the value as a string. An error is returned if the value didn't exist.

func ValueD added in v1.0.1

func ValueD(key, defaultVal string) string

ValueD retrieves a value. If it doesn't exist it will returen defaultVal instead

func WithObject

func WithObject(descr Descriptor)

WithObject adds support for a specific object type.

Types

type CfgFile

type CfgFile struct {
	Values map[string]string `yaml:"values,inline"`
}

CfgFile is the structure of files the ConfigFileProvider uses.

type Descriptor

type Descriptor interface {
	Construct() Object
	Type() string     // "EP"
	Fields() []string // "ADDRESS", "TLS"
}

The Descriptor interface is used to marshal/unmarshal objects via key/values

func GenericObjectDescriptor

func GenericObjectDescriptor(
	Type string,
	Fields []string) Descriptor

GenericObjectDescriptor generates a ObjectDescriptor for a generic type object.

type Endpoint

type Endpoint struct {
	Address      string `yaml:"address"`
	TLS          string `yaml:"tls,omitempty"` // Empty is no TLS
	ServerCACert string `yaml:"server_ca_cert,omitempty"`
	ServerCert   string `yaml:"server_cert,omitempty"`
	ServerKey    string `yaml:"server_key,omitempty"`
	ClientCACert string `yaml:"client_ca_cert,omitempty"`
	ClientCert   string `yaml:"client_cert,omitempty"`
	ClientKey    string `yaml:"client_key,omitempty"`
	Path         string `yaml:"path,omitempty"`
}

Endpoint is either side of a client-server connection

func GetEndpoint

func GetEndpoint(name string) (*Endpoint, error)

GetEndpoint retrieves and endpoint from the external context

func (*Endpoint) Fields

func (e *Endpoint) Fields() map[string]string

Fields returns the full set of fields with values

func (*Endpoint) Get

func (e *Endpoint) Get(field string) (val string, err error)

Get field of the endpoing

func (*Endpoint) GetClientTLSConfig added in v1.0.1

func (e *Endpoint) GetClientTLSConfig() (*tls.Config, error)

GetClientTLSConfig returns a *tls.Config suitable for a server We need the following values from the endpoint - TLS=[none|server|mtls] - ServerCACert=[file|string|"external"] - ClientCertificate=[file|string] - ClientPrivateKey=[file|string]

func (*Endpoint) GetServerTLSConfig added in v1.0.1

func (e *Endpoint) GetServerTLSConfig() (*tls.Config, error)

GetServerTLSConfig returns a *tls.Config suitable for a server We need the following values from the endpoint - TLS=[none|server|mtls] - ServerCertificate=[file|string] - ServerPrivateKey=[file|string] - ClientCACert=[file|string]

func (*Endpoint) GrpcClientConn

func (e *Endpoint) GrpcClientConn(ctx context.Context, options ...grpc.DialOption) (*grpc.ClientConn, error)

GrpcClientConn creates a client grpc connection to the endpoint

func (*Endpoint) GrpcServerListener

func (e *Endpoint) GrpcServerListener(allInterfaces bool, options ...grpc.ServerOption) (*grpc.Server, net.Listener, error)

GrpcServerListener creates a grpc server and listener on the endpoint

func (*Endpoint) HTTPClientConnInfo added in v1.0.1

func (e *Endpoint) HTTPClientConnInfo(name string) (client *http.Client, u url.URL, err error)

HTTPClientConnInfo creates a client and an url, which the user can use to setup the client connection to the server.

func (*Endpoint) HTTPServerListener added in v1.0.1

func (e *Endpoint) HTTPServerListener(allInterfaces bool) (*http.Server, net.Listener, error)
HTTPServerListener creates a http.Server and a net.Listener to be used by a http server.

...

ep,_ := xvals.GetEndpoint("my_endpoint")
server,listener,_ := ep.HTTPServerListener(true)
server.Handler = http.NotFoundHandler()
server.Serve(listener)

...

func (*Endpoint) Set

func (e *Endpoint) Set(field, val string) error

Set field of the endpoint

func (*Endpoint) Type

func (e *Endpoint) Type() string

Type returns the type name of the endpoint

func (*Endpoint) UseTLS added in v1.0.1

func (e *Endpoint) UseTLS() bool

UseTLS returns false if TLS should not be considered

func (*Endpoint) Write

func (e *Endpoint) Write(name string, w io.Writer)

type GenericObject

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

GenericObject provides a default implementation for objects. It can be used for all objects that has no need for a formal go struct as base for the type.

func (*GenericObject) Fields

func (o *GenericObject) Fields() map[string]string

Fields returns all fields of the object with their values

func (*GenericObject) Get

func (o *GenericObject) Get(field string) (value string, err error)

Get returns the value of a field

func (*GenericObject) Set

func (o *GenericObject) Set(key, val string) error

Set the value of a field

func (*GenericObject) Type

func (o *GenericObject) Type() string

Type returns the type of the object

type Object

type Object interface {
	Type() string
	Fields() map[string]string
	Get(field string) (value string, err error)
	Set(field, val string) error
}

Object is the interface all supported objects must implement. It is described by a Descriptor, which is used to generate the object.

A field is defined by a key in the format:

		<TYPE>_<NAME>_<FIELD>=<VALUE>
     <----    KEY    ---->

An Object is made up of the sum of it's keys.

func GetObject

func GetObject(typ, name string) (Object, error)

GetObject retrieves an object based on type and name

func NewObject

func NewObject(typ, name string) (Object, error)

NewObject creates a new object with the name and type and adds it to default store.

type ObjectStore

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

An ObjectStore is a storage where objects described according can be stored. It uses xvals and descriptors to extract the keys/values that are used to build the objects.

func NewObjectStore

func NewObjectStore() *ObjectStore

NewObjectStore creates a new store for objects.

func (*ObjectStore) AddDescriptor

func (c *ObjectStore) AddDescriptor(descriptor Descriptor)

AddDescriptor lets the store use a new descriptor for objects.

func (*ObjectStore) Get

func (c *ObjectStore) Get(typ, name string) (Object, error)

Get an object based on type and name

func (*ObjectStore) New

func (c *ObjectStore) New(typ, name string) (Object, error)

New creates a new Object based on type name and object name

func (*ObjectStore) Objects

func (c *ObjectStore) Objects() map[string]Object

Objects returns the objects known to the store.

func (*ObjectStore) Reload

func (c *ObjectStore) Reload(kv map[string]string)

Reload the store from the set of key/values

type ProfileFile added in v1.0.3

type ProfileFile struct {
	CurrentProfile string                       `yaml:"current_profile"`
	Profiles       map[string]map[string]string `yaml:"profiles"`
}

type XvalProvider

type XvalProvider interface {

	// Get Value or error
	Value(key string) (val string, err error)

	// Dump all values from the source
	Dump() map[string]string

	// Reload the values from the source
	// In case of an error, the variables will simply not be available
	// An error message should be logged in that case.
	Reload()
}

XvalProvider is the interface all providers of values must implement

func WithConfigFile

func WithConfigFile(filename string) XvalProvider

WithConfigFile adds a config file to the xval context. More than one file can be added. First added file has highest priority. Last added least priority.

func WithEnvironment

func WithEnvironment() XvalProvider

WithEnvironment adds environmental variables to the xval context. Will panic in case of errors

func WithMap

func WithMap(src map[string]string) XvalProvider

WithMap adds a map to the xval context.

func WithProfile added in v1.0.3

func WithProfile(profileFilePath string) XvalProvider

WithProfile adds a file that has a one or several profiles, which of one is the current profile. Each profile is a mapProvider

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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