config

package
v1.9.3 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2022 License: MIT Imports: 16 Imported by: 0

README

Config pakcage

This package will make a global config management package for an app. This package work wil component who's will make the real intelligence of the config. For example, the main config file is not existing into this config, because is generated by the sum of all component config part.

Exmaple of implement

You can follow the initialization define into the cobra package Here we will define the intialization of the config package.

Main init of config :

Make a package's file to be called by yours application command or routers Into this file we will use some import

import (
    "fmt"
    "net/http"

    liberr "github.com/nabbar/golib/errors"
    libsts "github.com/nabbar/golib/status"
    liblog "github.com/nabbar/golib/logger"
    librtr "github.com/nabbar/golib/router"
	
    cmphea "github.com/nabbar/golib/config/components/head"
    cmphtp "github.com/nabbar/golib/config/components/http"
    cmplog "github.com/nabbar/golib/config/components/log"
    cmptls "github.com/nabbar/golib/config/components/tls"

    compkg "../pkg"
)

Some constant to prevents error on copy/paste :

const (
    ConfigKeyHead = "headers"
    ConfigKeyHttp = "servers"
    ConfigKeyLog  = "log"
    ConfigKeyTls  = "tls"
)

This function will init the libs and return the lib resource. This is an example, but you can create your own component to add it into you config. The config can have multi instance of same component type but with different config key. As That, you can for example define a TLS config for HTTP server, a TLS config for a client, ...

func SetConfig(lvl liblog.Level, handler map[string]http.Handler) {
    compkg.GetConfig().ComponentSet(ConfigKeyHead, cmphea.New())
    compkg.GetConfig().ComponentSet(ConfigKeyLog, cmplog.New(lvl, compkg.GetLogger))
    compkg.GetConfig().ComponentSet(ConfigKeyTls, cmptls.New())
    compkg.GetConfig().ComponentSet(ConfigKeyHttp, cmphtp.New(_ConfigKeyTls, _ConfigKeyLog, handler))
}

// This function will return the router header based of the component header stored into the config
func GetHeader() librtr.Headers {
    if cmp := cmphea.Load(compkg.GetConfig().ComponentGet, _ConfigKeyHead); cmp != nil {
        return cmp.GetHeaders()
    } else {
        GetLog().Fatal("component '%s' is not initialized", _ConfigKeyHead)
        return nil
    }
}

// This function will return the logger for the application. 
// If the component is not started, this function will return the root logger  
func GetLog() liblog.Logger {
    if !compkg.GetConfig().ComponentIsStarted() {
        return nil
    }

    if cmp := cmplog.Load(compkg.GetConfig().ComponentGet, _ConfigKeyLog); cmp != nil {
        return cmp.Log()
    } else {
        compkg.GetLogger().Error("component '%s' is not initialized", _ConfigKeyLog)
        return compkg.GetLogger()
    }
}

This function will connect the status package of golib with the httpserver package stored into the config :

// This function can be call by the implementation of Status Package to expose the status of the pool web server
// This function will update the status after each reload the pool web server.
func SetRouteStatus(sts libsts.RouteStatus) {
    compkg.GetConfig().RegisterFuncReloadAfter(func() liberr.Error {
        var cmp cmphtp.ComponentHttp

		// If component has not been started, skill the function
        if !compkg.GetConfig().ComponentIsStarted() {
            return nil
        }

		// if cannot access to the Http component, generate an error
        if cmp = cmphtp.Load(compkg.GetConfig().ComponentGet, ConfigKeyHttp); cmp == nil {
            return ErrorComponentNotInitialized.ErrorParent(fmt.Errorf("component '%s'", ConfigKeyHttp))
        }

		// Get the Pool Server
        pool := cmp.GetPool()
        pool.StatusRoute(_ConfigKeyHttp, GetRouteStatusMessage, sts)
		
		// Don't forget to update the component pool
        cmp.SetPool(pool)

        return nil
    })
}

To generate the config example, just call this function :

    compkg.GetConfig().DefaultConfig()

This function will associate the config Key with the component default config into a main buffer to return it. As that, config can be extended easily with many component and the config is automatically managed.

Documentation

Index

Constants

View Source
const (
	ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgConfig
	ErrorConfigMissingViper
	ErrorComponentNotFound
	ErrorComponentFlagError
	ErrorComponentConfigNotFound
	ErrorComponentConfigError
	ErrorComponentStart
	ErrorComponentReload
)
View Source
const (
	MinErrorComponentAws      = ErrorParamsEmpty + 10
	MinErrorComponentDatabase = MinErrorComponentAws + 10
	MinErrorComponentHead     = MinErrorComponentDatabase + 10
	MinErrorComponentHttp     = MinErrorComponentHead + 10
	MinErrorComponentLog      = MinErrorComponentHttp + 10
	MinErrorComponentMail     = MinErrorComponentLog + 10
	MinErrorComponentNats     = MinErrorComponentMail + 10
	MinErrorComponentNutsDB   = MinErrorComponentNats + 10
	MinErrorComponentRequest  = MinErrorComponentNutsDB + 10
	MinErrorComponentSmtp     = MinErrorComponentRequest + 10
	MinErrorComponentTls      = MinErrorComponentSmtp + 10
)
View Source
const JSONIndent = "  "

Variables

This section is empty.

Functions

func IsCodeError

func IsCodeError() bool

Types

type Component

type Component interface {
	// Type return the component type.
	Type() string

	// Init is called by Config to register some function and value to the component instance.
	Init(key string, ctx FuncContext, get FuncComponentGet, vpr FuncComponentViper)

	// RegisterFuncStart is called to register the function to be called before and after the start function.
	RegisterFuncStart(before, after func(cpt Component) liberr.Error)

	// RegisterFuncReload is called to register the function to be called before and after the reload function.
	RegisterFuncReload(before, after func(cpt Component) liberr.Error)

	// RegisterFlag can be called to register flag to a spf cobra command and link it with viper
	// to retrieve it into the config viper.
	// The key will be use to stay config organisation by compose flag as key.config_key.
	RegisterFlag(Command *spfcbr.Command, Viper *spfvpr.Viper) error

	// IsStarted is trigger by the Config interface with function ComponentIsStarted.
	// This function can be usefull to know if the start server function is still call.
	IsStarted() bool

	// IsRunning is trigger by the Config interface with function ComponentIsRunning.
	// This function can be usefully to know if the component server function is still call.
	// The atLeast param is used to know if the function must return true on first server is running
	// or if all server must be running to return true.
	IsRunning(atLeast bool) bool

	// Start is called by the Config interface when the global configuration as been started
	// This function can be usefull to start server in go routine with a configuration stored
	// itself.
	Start(getCfg FuncComponentConfigGet) liberr.Error

	// Reload is called by the Config interface when the global configuration as been updated
	// It receives a func as param to grab a config model by sending a model structure.
	// It must configure itself, and stop / start his server if possible or return an error.
	Reload(getCfg FuncComponentConfigGet) liberr.Error

	// Stop is called by the Config interface when global context is done.
	// The context done can arrive by stopping the application or by received a signal KILL/TERM.
	// This function must stop cleanly the component.
	Stop()

	// DefaultConfig is called by Config.GetDefault.
	// It must return a slice of byte containing the default json config for this component.
	DefaultConfig(indent string) []byte

	// Dependencies is called by Config to define if this component need other component.
	// Each other component can be call by calling Config.Get
	Dependencies() []string
}

type ComponentList

type ComponentList interface {
	// ComponentHas return true if the key is a registered Component
	ComponentHas(key string) bool

	// ComponentType return the Component Type of the registered key.
	ComponentType(key string) string

	// ComponentGet return the given component associated with the config Key.
	// The component can be transTyped to other interface to be exploited
	ComponentGet(key string) Component

	// ComponentDel remove the given Component key from the config.
	ComponentDel(key string)

	// ComponentSet stores the given Component with a key.
	ComponentSet(key string, cpt Component)

	// ComponentList returns a map of stored couple keyType and Component
	ComponentList() map[string]Component

	// ComponentKeys returns a slice of stored Component keys
	ComponentKeys() []string

	// ComponentStart trigger the Start function of each Component.
	// This function will keep the dependencies of each Component.
	// This function will stop the Start sequence on any error triggered.
	ComponentStart(getCfg FuncComponentConfigGet) liberr.Error

	// ComponentIsStarted will trigger the IsStarted function of all registered component.
	// If any component return false, this func return false.
	ComponentIsStarted() bool

	// ComponentReload trigger the Reload function of each Component.
	// This function will keep the dependencies of each Component.
	// This function will stop the Reload sequence on any error triggered.
	ComponentReload(getCfg FuncComponentConfigGet) liberr.Error

	// ComponentStop trigger the Stop function of each Component.
	// This function will not keep the dependencies of each Component.
	ComponentStop()

	// ComponentIsRunning will trigger the IsRunning function of all registered component.
	// If any component return false, this func return false.
	ComponentIsRunning(atLeast bool) bool

	// DefaultConfig aggregates all registered components' default config
	// Returns a filled buffer with a complete config json model
	DefaultConfig() io.Reader

	// RegisterFlag can be called to register flag to a spf cobra command and link it with viper
	// to retrieve it into the config viper.
	// The key will be use to stay config organisation by compose flag as key.config_key.
	RegisterFlag(Command *spfcbr.Command, Viper *spfvpr.Viper) error
}

type Config

type Config interface {

	// Context return the current context pointer
	Context() context.Context

	// ContextMerge trigger the golib/context/config interface
	// and will merge the stored context value into current context
	ContextMerge(ctx libctx.Config) bool

	// ContextStore trigger the golib/context/config interface
	// and will store a context value into current context
	ContextStore(key string, cfg interface{})

	// ContextLoad trigger the golib/context/config interface
	// and will restore a context value or nil
	ContextLoad(key string) interface{}

	// ContextSetCancel allow to register a custom function called on cancel context.
	// On context cancel event or signal kill, term... this function will be called
	// before config stop and main context cancel function
	ContextSetCancel(fct func())

	RegisterFuncViper(fct func() libvpr.Viper)

	// Start will trigger the start function of all registered component.
	// If any component return an error, this func will stop the start
	// process and return the error.
	Start() liberr.Error

	// RegisterFuncStartBefore allow to register a func to be call when the config Start
	// is trigger. This func is call before the start sequence.
	RegisterFuncStartBefore(fct func() liberr.Error)

	// RegisterFuncStartAfter allow to register a func to be call when the config Start
	// is trigger. This func is call after the start sequence.
	RegisterFuncStartAfter(fct func() liberr.Error)

	// Reload triggers the Reload function of each registered Component.
	Reload() liberr.Error

	// RegisterFuncReloadBefore allow to register a func to be call when the config Reload
	// is trigger. This func is call before the reload sequence.
	RegisterFuncReloadBefore(fct func() liberr.Error)

	// RegisterFuncReloadAfter allow to register a func to be call when the config Reload
	// is trigger. This func is call after the reload sequence.
	RegisterFuncReloadAfter(fct func() liberr.Error)

	// Stop will trigger the stop function of all registered component.
	// All component must stop cleanly.
	Stop()

	// RegisterFuncStopBefore allow to register a func to be call when the config Stop
	// is trigger. This func is call before the stop sequence.
	RegisterFuncStopBefore(fct func())

	// RegisterFuncStopAfter allow to register a func to be call when the config Stop
	// is trigger. This func is call after the stop sequence.
	RegisterFuncStopAfter(fct func())

	// Shutdown will trigger all stop function.
	// This function will call the Stop function and the private function cancel.
	// This will stop all process and do like a SIGTERM/SIGINT signal.
	// This will finish by an os.Exit with the given parameter code.
	Shutdown(code int)

	/*
		// Section Component : github.com/nabbar/golib/config
	*/
	ComponentList
}

func New

func New() Config

type FuncComponentConfigGet

type FuncComponentConfigGet func(key string, model interface{}) liberr.Error

type FuncComponentGet

type FuncComponentGet func(key string) Component

type FuncComponentViper added in v1.8.10

type FuncComponentViper func() *spfvpr.Viper

type FuncContext

type FuncContext func() context.Context

Directories

Path Synopsis
components
aws
log
tls

Jump to

Keyboard shortcuts

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