diff --git a/archive/archive.go b/archive/archive.go index 822557b..aede8b0 100644 --- a/archive/archive.go +++ b/archive/archive.go @@ -203,7 +203,7 @@ func ExtractAll(src libiot.FileProgress, originalName, outputPath string, defaul func CreateArchive(archiveType ArchiveType, archive libiot.FileProgress, stripPath string, comment string, pathContent ...string) (created bool, err liberr.Error) { if len(pathContent) < 1 { //nolint #goerr113 - return false, ErrorParamsEmpty.ErrorParent(fmt.Errorf("pathContent is empty")) + return false, ErrorParamEmpty.ErrorParent(fmt.Errorf("pathContent is empty")) } switch archiveType { diff --git a/archive/error.go b/archive/error.go index 7c7159a..8926084 100644 --- a/archive/error.go +++ b/archive/error.go @@ -26,10 +26,14 @@ package archive -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgArchive + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgArchive ErrorFileSeek ErrorFileOpen ErrorFileClose @@ -39,22 +43,16 @@ const ( ErrorIOCopy ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorFileSeek: return "cannot seek into file" @@ -72,5 +70,5 @@ func getMessage(code errors.CodeError) (message string) { return "error occurs when io copy" } - return "" + return liberr.NullMessage } diff --git a/aws/configAws/error.go b/aws/configAws/error.go index de79b76..893bf22 100644 --- a/aws/configAws/error.go +++ b/aws/configAws/error.go @@ -26,6 +26,8 @@ package configAws import ( + "fmt" + liberr "github.com/nabbar/golib/errors" ) @@ -40,16 +42,13 @@ const ( ErrorCredentialsInvalid ) -var isErrInit = liberr.ExistInMapMessage(ErrorAwsError) - func init() { + if liberr.ExistInMapMessage(ErrorAwsError) { + panic(fmt.Errorf("error code collision")) + } liberr.RegisterIdFctMessage(ErrorAwsError, getMessage) } -func IsErrorInit() bool { - return isErrInit -} - func getMessage(code liberr.CodeError) string { switch code { case ErrorAwsError: @@ -70,5 +69,5 @@ func getMessage(code liberr.CodeError) string { return "the specified credentials seems to be incorrect" } - return liberr.UNK_MESSAGE + return liberr.NullMessage } diff --git a/aws/configAws/interface.go b/aws/configAws/interface.go index 6ef74c5..58e9836 100644 --- a/aws/configAws/interface.go +++ b/aws/configAws/interface.go @@ -53,6 +53,18 @@ func NewConfigJsonUnmashal(p []byte) (libaws.Config, errors.Error) { }, nil } +func NewConfigStatusJsonUnmashal(p []byte) (libaws.Config, errors.Error) { + c := ModelStatus{} + if err := json.Unmarshal(p, &c); err != nil { + return nil, ErrorConfigJsonUnmarshall.ErrorParent(err) + } + + return &awsModel{ + Model: c.Config, + retryer: nil, + }, nil +} + func NewConfig(bucket, accessKey, secretKey, region string) libaws.Config { return &awsModel{ Model: Model{ diff --git a/aws/configAws/models.go b/aws/configAws/models.go index 1e962c9..c20c0c3 100644 --- a/aws/configAws/models.go +++ b/aws/configAws/models.go @@ -31,6 +31,8 @@ import ( "net" "net/url" + libsts "github.com/nabbar/golib/status/config" + sdkaws "github.com/aws/aws-sdk-go-v2/aws" libval "github.com/go-playground/validator/v10" "github.com/nabbar/golib/errors" @@ -44,6 +46,11 @@ type Model struct { Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket" toml:"bucket" validate:"printascii,omitempty"` } +type ModelStatus struct { + Config Model `json:"config" yaml:"config" toml:"config" mapstructure:"config" validate:"required,dive"` + Status libsts.ConfigStatus `json:"status" yaml:"status" toml:"status" mapstructure:"status" validate:"required,dive"` +} + type awsModel struct { Model retryer func() sdkaws.Retryer @@ -70,6 +77,10 @@ func (c *awsModel) Validate() errors.Error { return nil } +func (c *awsModel) GetAccessKey() string { + return c.AccessKey +} + func (c *awsModel) SetCredentials(accessKey, secretKey string) { c.AccessKey = accessKey c.SecretKey = secretKey diff --git a/aws/configCustom/error.go b/aws/configCustom/error.go index 3e0913a..6282934 100644 --- a/aws/configCustom/error.go +++ b/aws/configCustom/error.go @@ -26,6 +26,8 @@ package configCustom import ( + "fmt" + liberr "github.com/nabbar/golib/errors" ) @@ -39,16 +41,13 @@ const ( ErrorCredentialsInvalid ) -var isErrInit = liberr.ExistInMapMessage(ErrorAwsError) - func init() { + if liberr.ExistInMapMessage(ErrorAwsError) { + panic(fmt.Errorf("error code collision")) + } liberr.RegisterIdFctMessage(ErrorAwsError, getMessage) } -func IsErrorInit() bool { - return isErrInit -} - func getMessage(code liberr.CodeError) string { switch code { case ErrorAwsError: @@ -67,5 +66,5 @@ func getMessage(code liberr.CodeError) string { return "the specified credentials seems to be incorrect" } - return liberr.UNK_MESSAGE + return liberr.NullMessage } diff --git a/aws/configCustom/interface.go b/aws/configCustom/interface.go index 433b3e9..531c6a6 100644 --- a/aws/configCustom/interface.go +++ b/aws/configCustom/interface.go @@ -35,14 +35,14 @@ import ( sdkaws "github.com/aws/aws-sdk-go-v2/aws" sdkcrd "github.com/aws/aws-sdk-go-v2/credentials" libaws "github.com/nabbar/golib/aws" - "github.com/nabbar/golib/errors" + liberr "github.com/nabbar/golib/errors" ) func GetConfigModel() interface{} { return Model{} } -func NewConfigJsonUnmashal(p []byte) (libaws.Config, errors.Error) { +func NewConfigJsonUnmashal(p []byte) (libaws.Config, liberr.Error) { c := Model{} if err := json.Unmarshal(p, &c); err != nil { return nil, ErrorConfigJsonUnmarshall.ErrorParent(err) @@ -55,6 +55,19 @@ func NewConfigJsonUnmashal(p []byte) (libaws.Config, errors.Error) { }, nil } +func NewConfigStatusJsonUnmashal(p []byte) (libaws.Config, liberr.Error) { + c := ModelStatus{} + if err := json.Unmarshal(p, &c); err != nil { + return nil, ErrorConfigJsonUnmarshall.ErrorParent(err) + } + + return &awsModel{ + Model: c.Config, + retryer: nil, + mapRegion: nil, + }, nil +} + func NewConfig(bucket, accessKey, secretKey string, endpoint *url.URL, region string) libaws.Config { return &awsModel{ Model: Model{ @@ -91,7 +104,7 @@ func (c *awsModel) Clone() libaws.Config { } } -func (c *awsModel) GetConfig(ctx context.Context, cli *http.Client) (*sdkaws.Config, errors.Error) { +func (c *awsModel) GetConfig(ctx context.Context, cli *http.Client) (*sdkaws.Config, liberr.Error) { cfg := sdkaws.NewConfig() diff --git a/aws/configCustom/models.go b/aws/configCustom/models.go index 2dbfe67..662d7cf 100644 --- a/aws/configCustom/models.go +++ b/aws/configCustom/models.go @@ -34,9 +34,10 @@ import ( sdkaws "github.com/aws/aws-sdk-go-v2/aws" libval "github.com/go-playground/validator/v10" - "github.com/nabbar/golib/errors" - "github.com/nabbar/golib/httpcli" - "github.com/nabbar/golib/logger" + liberr "github.com/nabbar/golib/errors" + libhtc "github.com/nabbar/golib/httpcli" + liblog "github.com/nabbar/golib/logger" + libsts "github.com/nabbar/golib/status/config" ) type Model struct { @@ -47,6 +48,11 @@ type Model struct { Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket" toml:"bucket" validate:"omitempty,hostname"` } +type ModelStatus struct { + Config Model `json:"config" yaml:"config" toml:"config" mapstructure:"config" validate:"required,dive"` + Status libsts.ConfigStatus `json:"status" yaml:"status" toml:"status" mapstructure:"status" validate:"required,dive"` +} + type awsModel struct { Model @@ -55,7 +61,7 @@ type awsModel struct { mapRegion map[string]*url.URL } -func (c *awsModel) Validate() errors.Error { +func (c *awsModel) Validate() liberr.Error { err := ErrorConfigValidator.Error(nil) if er := libval.New().Struct(c); er != nil { @@ -93,6 +99,10 @@ func (c *awsModel) Validate() errors.Error { return err } +func (c *awsModel) GetAccessKey() string { + return c.AccessKey +} + func (c *awsModel) SetCredentials(accessKey, secretKey string) { c.AccessKey = accessKey c.SecretKey = secretKey @@ -102,7 +112,7 @@ func (c *awsModel) ResetRegionEndpoint() { c.mapRegion = make(map[string]*url.URL) } -func (c *awsModel) RegisterRegionEndpoint(region string, endpoint *url.URL) errors.Error { +func (c *awsModel) RegisterRegionEndpoint(region string, endpoint *url.URL) liberr.Error { if endpoint == nil && c.endpoint != nil { endpoint = c.endpoint } else if endpoint == nil && c.Endpoint != "" { @@ -137,7 +147,7 @@ func (c *awsModel) RegisterRegionEndpoint(region string, endpoint *url.URL) erro return nil } -func (c *awsModel) RegisterRegionAws(endpoint *url.URL) errors.Error { +func (c *awsModel) RegisterRegionAws(endpoint *url.URL) liberr.Error { if endpoint == nil && c.endpoint != nil { endpoint = c.endpoint } else if endpoint == nil && c.Endpoint != "" { @@ -231,7 +241,7 @@ func (c *awsModel) ResolveEndpoint(service, region string) (sdkaws.Endpoint, err }, nil } - logger.DebugLevel.Logf("Called ResolveEndpoint for service '%s' / region '%s' with nil endpoint", service, region) + liblog.DebugLevel.Logf("Called ResolveEndpoint for service '%s' / region '%s' with nil endpoint", service, region) return sdkaws.Endpoint{}, ErrorEndpointInvalid.Error(nil) } @@ -243,12 +253,12 @@ func (c *awsModel) SetRetryer(retryer func() sdkaws.Retryer) { c.retryer = retryer } -func (c awsModel) Check(ctx context.Context) errors.Error { +func (c awsModel) Check(ctx context.Context) liberr.Error { var ( cfg *sdkaws.Config con net.Conn err error - e errors.Error + e liberr.Error ) if cfg, e = c.GetConfig(ctx, nil); e != nil { @@ -268,8 +278,8 @@ func (c awsModel) Check(ctx context.Context) errors.Error { } d := net.Dialer{ - Timeout: httpcli.ClientTimeout5Sec, - KeepAlive: httpcli.ClientTimeout5Sec, + Timeout: libhtc.ClientTimeout5Sec, + KeepAlive: libhtc.ClientTimeout5Sec, } if c.endpoint.Port() == "" && c.endpoint.Scheme == "http" { diff --git a/aws/helper/error.go b/aws/helper/error.go index ca5ae9f..04d91bf 100644 --- a/aws/helper/error.go +++ b/aws/helper/error.go @@ -26,12 +26,14 @@ package helper import ( - errors "github.com/nabbar/golib/errors" + "fmt" + + liberr "github.com/nabbar/golib/errors" ) const ( - // minmal are errors.MIN_AVAILABLE + get a hope free range 1000 + 10 for aws-config errors. - ErrorResponse errors.CodeError = iota + errors.MinPkgAws + 60 + // minmal are liberr.MIN_AVAILABLE + get a hope free range 1000 + 10 for aws-config liberr. + ErrorResponse liberr.CodeError = iota + liberr.MinPkgAws + 60 ErrorConfigEmpty ErrorAwsEmpty ErrorAws @@ -39,17 +41,20 @@ const ( ErrorParamsEmpty ) -var isErrInit = errors.ExistInMapMessage(ErrorResponse) +var isErrInit = liberr.ExistInMapMessage(ErrorResponse) func init() { - errors.RegisterIdFctMessage(ErrorResponse, getMessage) + if liberr.ExistInMapMessage(ErrorResponse) { + panic(fmt.Errorf("error code collision with package golib/aws/helpers")) + } + liberr.RegisterIdFctMessage(ErrorResponse, getMessage) } func IsErrorInit() bool { return isErrInit } -func getMessage(code errors.CodeError) string { +func getMessage(code liberr.CodeError) string { switch code { case ErrorResponse: return "calling aws api occurred a response error" @@ -65,5 +70,5 @@ func getMessage(code errors.CodeError) string { return "at least one parameters needed is empty" } - return errors.UNK_MESSAGE + return liberr.NullMessage } diff --git a/aws/interface.go b/aws/interface.go index d1795ec..9c76728 100644 --- a/aws/interface.go +++ b/aws/interface.go @@ -48,6 +48,7 @@ type Config interface { Check(ctx context.Context) liberr.Error Validate() liberr.Error + GetAccessKey() string SetCredentials(accessKey, secretKey string) ResetRegionEndpoint() RegisterRegionEndpoint(region string, endpoint *url.URL) liberr.Error diff --git a/aws/object/object.go b/aws/object/object.go index 0ad0e88..f3b325a 100644 --- a/aws/object/object.go +++ b/aws/object/object.go @@ -81,7 +81,7 @@ func (cli *client) WalkPrefix(prefix string, f WalkFunc) liberr.Error { var ( e liberr.Error - t *string + t = sdkaws.String("") ) for { diff --git a/aws/object/version.go b/aws/object/version.go index df893fa..daa417e 100644 --- a/aws/object/version.go +++ b/aws/object/version.go @@ -77,8 +77,8 @@ func (cli *client) VersionWalkPrefix(prefix string, fv VersionWalkFunc, fd DelMa var ( e liberr.Error - km *string - mi *string + km = sdkaws.String("") + mi = sdkaws.String("") ) for { diff --git a/certificates/error.go b/certificates/error.go index 8a6f726..c423be0 100644 --- a/certificates/error.go +++ b/certificates/error.go @@ -26,10 +26,14 @@ package certificates -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgCertificate + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgCertificate ErrorFileStat ErrorFileRead ErrorFileEmpty @@ -39,22 +43,18 @@ const ( ErrorValidatorError ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/certificates")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: + case liberr.UNK_ERROR: return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorFileStat: return "cannot get file stat" @@ -72,5 +72,5 @@ func getMessage(code errors.CodeError) (message string) { return "tls : invalid config" } - return "" + return liberr.NullMessage } diff --git a/certificates/model.go b/certificates/model.go index 41c9117..cf08bf9 100644 --- a/certificates/model.go +++ b/certificates/model.go @@ -53,7 +53,7 @@ type config struct { func (c *config) checkFile(pemFiles ...string) liberr.Error { for _, f := range pemFiles { if f == "" { - return ErrorParamsEmpty.Error(nil) + return ErrorParamEmpty.Error(nil) } if _, e := os.Stat(f); e != nil { @@ -157,7 +157,7 @@ func (c *config) AddCertificatePairString(key, crt string) liberr.Error { crt = strings.TrimSpace(crt) if len(key) < 1 || len(crt) < 1 { - return ErrorParamsEmpty.Error(nil) + return ErrorParamEmpty.Error(nil) } p, err := tls.X509KeyPair([]byte(crt), []byte(key)) diff --git a/config/component.go b/config/component.go index 2b0da13..613b3a7 100644 --- a/config/component.go +++ b/config/component.go @@ -37,7 +37,7 @@ type Component interface { 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) + Init(key string, ctx FuncContext, get FuncComponentGet, vpr FuncComponentViper, sts FuncRouteStatus) // RegisterFuncStart is called to register the function to be called before and after the start function. RegisterFuncStart(before, after func(cpt Component) liberr.Error) diff --git a/config/components/aws/default.go b/config/components/aws/default.go index 53cfd0f..bbbd1d3 100644 --- a/config/components/aws/default.go +++ b/config/components/aws/default.go @@ -35,6 +35,7 @@ import ( cfgcus "github.com/nabbar/golib/aws/configCustom" libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" + libsts "github.com/nabbar/golib/status/config" spfcbr "github.com/spf13/cobra" spfvbr "github.com/spf13/viper" ) @@ -47,6 +48,15 @@ var _defaultConfigStandard = []byte(`{ "endpoint": "" }`) +var _defaultConfigStandardWithStatus = []byte(`{ + "bucket": "", + "accesskey": "", + "secretkey": "", + "region": "", + "endpoint": "", + "status":` + string(libsts.DefaultConfig(libcfg.JSONIndent+libcfg.JSONIndent)) + ` +}`) + var _defaultConfigCustom = []byte(`{ "bucket": "", "accesskey": "", @@ -55,18 +65,35 @@ var _defaultConfigCustom = []byte(`{ "endpoint": "" }`) +var _defaultConfigCustomWithStatus = []byte(`{ + "bucket": "", + "accesskey": "", + "secretkey": "", + "region": "", + "endpoint": "", + "status":` + string(libsts.DefaultConfig(libcfg.JSONIndent+libcfg.JSONIndent)) + ` +}`) + var _defaultConfig = _defaultConfigCustom func SetDefaultConfig(cfg []byte) { _defaultConfig = cfg } -func SetDefaultConfigStandard() { - _defaultConfig = _defaultConfigStandard +func SetDefaultConfigStandard(withStatus bool) { + if withStatus { + _defaultConfig = _defaultConfigStandardWithStatus + } else { + _defaultConfig = _defaultConfigStandard + } } -func SetDefaultConfigCustom() { - _defaultConfig = _defaultConfigCustom +func SetDefaultConfigCustom(withStatus bool) { + if withStatus { + _defaultConfig = _defaultConfigCustomWithStatus + } else { + _defaultConfig = _defaultConfigCustom + } } func DefaultConfig(indent string) []byte { @@ -104,18 +131,44 @@ func (c *componentAws) RegisterFlag(Command *spfcbr.Command, Viper *spfvbr.Viper return nil } -func (c *componentAws) _getConfig(getCfg libcfg.FuncComponentConfigGet) (libaws.Config, liberr.Error) { +func (c *componentAws) _getConfig(getCfg libcfg.FuncComponentConfigGet) (libaws.Config, *libsts.ConfigStatus, liberr.Error) { var ( vpr = c.vpr() cfg libaws.Config + sts *libsts.ConfigStatus err liberr.Error ) switch c.d { + case ConfigCustomStatus: + cnf := cfgcus.ModelStatus{} + if e := getCfg(c.key, &cnf); e != nil { + return nil, nil, ErrorParamInvalid.Error(e) + } + if s := vpr.GetString(c.key + ".access-key"); s != "" { + cnf.Config.AccessKey = s + } + if s := vpr.GetString(c.key + ".secret-key"); s != "" { + cnf.Config.SecretKey = s + } + if s := vpr.GetString(c.key + ".bucket"); s != "" { + cnf.Config.Bucket = s + } + if s := vpr.GetString(c.key + ".region"); s != "" { + cnf.Config.Region = s + } + if s := vpr.GetString(c.key + ".endpoint"); s != "" { + cnf.Config.Endpoint = s + } + if cfg, err = c.d.NewFromModel(cnf); err != nil { + return nil, nil, err + } else { + sts = &cnf.Status + } case ConfigCustom: cnf := cfgcus.Model{} if e := getCfg(c.key, &cnf); e != nil { - return nil, ErrorParamsInvalid.Error(e) + return nil, nil, ErrorParamInvalid.Error(e) } if s := vpr.GetString(c.key + ".access-key"); s != "" { cnf.AccessKey = s @@ -133,12 +186,34 @@ func (c *componentAws) _getConfig(getCfg libcfg.FuncComponentConfigGet) (libaws. cnf.Endpoint = s } if cfg, err = c.d.NewFromModel(cnf); err != nil { - return nil, err + return nil, nil, err + } + case ConfigStandardStatus: + cnf := cfgstd.ModelStatus{} + if e := getCfg(c.key, &cnf); e != nil { + return nil, nil, ErrorParamInvalid.Error(e) + } + if s := vpr.GetString(c.key + ".access-key"); s != "" { + cnf.Config.AccessKey = s + } + if s := vpr.GetString(c.key + ".secret-key"); s != "" { + cnf.Config.SecretKey = s + } + if s := vpr.GetString(c.key + ".bucket"); s != "" { + cnf.Config.Bucket = s + } + if s := vpr.GetString(c.key + ".region"); s != "" { + cnf.Config.Region = s + } + if cfg, err = c.d.NewFromModel(cnf); err != nil { + return nil, nil, err + } else { + sts = &cnf.Status } case ConfigStandard: cnf := cfgstd.Model{} if e := getCfg(c.key, &cnf); e != nil { - return nil, ErrorParamsInvalid.Error(e) + return nil, nil, ErrorParamInvalid.Error(e) } if s := vpr.GetString(c.key + ".access-key"); s != "" { cnf.AccessKey = s @@ -153,13 +228,13 @@ func (c *componentAws) _getConfig(getCfg libcfg.FuncComponentConfigGet) (libaws. cnf.Region = s } if cfg, err = c.d.NewFromModel(cnf); err != nil { - return nil, err + return nil, nil, err } } if err = cfg.Validate(); err != nil { - return nil, ErrorConfigInvalid.Error(err) + return nil, nil, ErrorConfigInvalid.Error(err) } - return cfg, nil + return cfg, sts, nil } diff --git a/config/components/aws/driver.go b/config/components/aws/driver.go index a337549..24b51ca 100644 --- a/config/components/aws/driver.go +++ b/config/components/aws/driver.go @@ -39,13 +39,19 @@ type ConfigDriver uint8 const ( ConfigStandard ConfigDriver = iota + ConfigStandardStatus ConfigCustom + ConfigCustomStatus ) func DriverConfig(value int) ConfigDriver { switch value { case int(ConfigCustom): return ConfigCustom + case int(ConfigCustomStatus): + return ConfigCustomStatus + case int(ConfigStandardStatus): + return ConfigStandardStatus default: return ConfigStandard } @@ -55,6 +61,10 @@ func (a ConfigDriver) String() string { switch a { case ConfigCustom: return "Custom" + case ConfigCustomStatus: + return "CustomWithStatus" + case ConfigStandardStatus: + return "StandardWithStatus" default: return "Standard" } @@ -64,6 +74,10 @@ func (a ConfigDriver) Unmarshal(p []byte) (libaws.Config, liberr.Error) { switch a { case ConfigCustom: return cfgcus.NewConfigJsonUnmashal(p) + case ConfigCustomStatus: + return cfgcus.NewConfigStatusJsonUnmashal(p) + case ConfigStandardStatus: + return cfgstd.NewConfigStatusJsonUnmashal(p) default: return cfgstd.NewConfigJsonUnmashal(p) } @@ -71,8 +85,10 @@ func (a ConfigDriver) Unmarshal(p []byte) (libaws.Config, liberr.Error) { func (a ConfigDriver) Config(bucket, accessKey, secretKey string, region string, endpoint *url.URL) libaws.Config { switch a { - case ConfigCustom: + case ConfigCustom, ConfigCustomStatus: return cfgcus.NewConfig(bucket, accessKey, secretKey, endpoint, region) + case ConfigStandardStatus: + return cfgstd.NewConfig(bucket, accessKey, secretKey, region) default: return cfgstd.NewConfig(bucket, accessKey, secretKey, region) } @@ -82,6 +98,10 @@ func (a ConfigDriver) Model() interface{} { switch a { case ConfigCustom: return cfgcus.Model{} + case ConfigCustomStatus: + return cfgcus.ModelStatus{} + case ConfigStandardStatus: + return cfgstd.ModelStatus{} default: return cfgstd.Model{} } @@ -89,6 +109,18 @@ func (a ConfigDriver) Model() interface{} { func (a ConfigDriver) NewFromModel(i interface{}) (libaws.Config, liberr.Error) { switch a { + case ConfigCustomStatus: + if o, ok := i.(cfgcus.ModelStatus); !ok { + return nil, ErrorConfigInvalid.Error(nil) + } else { + return ConfigCustom.NewFromModel(o.Config) + } + case ConfigStandardStatus: + if o, ok := i.(cfgstd.ModelStatus); !ok { + return nil, ErrorConfigInvalid.Error(nil) + } else { + return ConfigStandard.NewFromModel(o.Config) + } case ConfigCustom: if o, ok := i.(cfgcus.Model); !ok { return nil, ErrorConfigInvalid.Error(nil) diff --git a/config/components/aws/errors.go b/config/components/aws/errors.go index f8bf944..710d9bc 100644 --- a/config/components/aws/errors.go +++ b/config/components/aws/errors.go @@ -27,13 +27,15 @@ package aws import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentAws - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentAws + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorStartComponent @@ -42,21 +44,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/aws")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -70,5 +68,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot retrieve default Logger" } - return "" + return liberr.NullMessage } diff --git a/config/components/aws/model.go b/config/components/aws/model.go index c30006d..f930a47 100644 --- a/config/components/aws/model.go +++ b/config/components/aws/model.go @@ -33,12 +33,16 @@ import ( libaws "github.com/nabbar/golib/aws" libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" + libsts "github.com/nabbar/golib/status" + stscfg "github.com/nabbar/golib/status/config" ) type componentAws struct { ctx libcfg.FuncContext get libcfg.FuncComponentGet vpr libcfg.FuncComponentViper + sts libcfg.FuncRouteStatus + key string fsa func(cpt libcfg.Component) liberr.Error @@ -46,10 +50,14 @@ type componentAws struct { fra func(cpt libcfg.Component) liberr.Error frb func(cpt libcfg.Component) liberr.Error + fsi libsts.FctInfo + fsh libsts.FctHealth + m sync.Mutex d ConfigDriver c func() *http.Client a libaws.AWS + s stscfg.ConfigStatus } func (c *componentAws) _getHttpClient() *http.Client { @@ -83,12 +91,16 @@ func (c *componentAws) _runCli(getCfg libcfg.FuncComponentConfigGet) liberr.Erro c.m.Lock() defer c.m.Unlock() - if cfg, err := c._getConfig(getCfg); err != nil { + if cfg, sts, err := c._getConfig(getCfg); err != nil { return err } else if cli, er := libaws.New(c.ctx(), cfg, c._getHttpClient()); er != nil { return er } else { c.a = cli + + if sts != nil && c.sts != nil && c.fsi != nil && c.fsh != nil { + sts.RegisterStatus(c.sts(), c.key, c.fsi, c.fsh) + } } return nil @@ -112,7 +124,7 @@ func (c *componentAws) Type() string { return ComponentType } -func (c *componentAws) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentAws) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/components/database/default.go b/config/components/database/default.go index 6139f13..5fc1b52 100644 --- a/config/components/database/default.go +++ b/config/components/database/default.go @@ -35,7 +35,7 @@ import ( libdbs "github.com/nabbar/golib/database" liberr "github.com/nabbar/golib/errors" liblog "github.com/nabbar/golib/logger" - libsts "github.com/nabbar/golib/status" + libsts "github.com/nabbar/golib/status/config" spfcbr "github.com/spf13/cobra" spfvbr "github.com/spf13/viper" ) @@ -153,7 +153,7 @@ func (c *componentDatabase) _getConfig(getCfg libcfg.FuncComponentConfigGet) (li } if err := getCfg(c.key, &cnf); err != nil { - return cnf, ErrorParamsInvalid.Error(err) + return cnf, ErrorParamInvalid.Error(err) } fct := func() liblog.Logger { diff --git a/config/components/database/errors.go b/config/components/database/errors.go index 9023f7d..a4fa1ef 100644 --- a/config/components/database/errors.go +++ b/config/components/database/errors.go @@ -27,13 +27,15 @@ package database import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentDatabase - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentDatabase + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorStartDatabase @@ -42,21 +44,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/database")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -70,5 +68,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot retrieve default Logger" } - return "" + return liberr.NullMessage } diff --git a/config/components/database/model.go b/config/components/database/model.go index 36ced31..fbfa4b8 100644 --- a/config/components/database/model.go +++ b/config/components/database/model.go @@ -139,7 +139,7 @@ func (c *componentDatabase) Type() string { return ComponentType } -func (c *componentDatabase) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentDatabase) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/components/head/errors.go b/config/components/head/errors.go index dc11bfb..1f80fe5 100644 --- a/config/components/head/errors.go +++ b/config/components/head/errors.go @@ -27,13 +27,15 @@ package head import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentHead - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentHead + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorReloadPoolServer @@ -41,21 +43,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/head")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -67,5 +65,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot update default TLS with new config" } - return "" + return liberr.NullMessage } diff --git a/config/components/head/model.go b/config/components/head/model.go index 1fb96ae..1ad14d4 100644 --- a/config/components/head/model.go +++ b/config/components/head/model.go @@ -74,7 +74,7 @@ func (c *componentHead) _runCli(getCfg libcfg.FuncComponentConfigGet) liberr.Err cnf := librtr.HeadersConfig{} if err := getCfg(c.key, &cnf); err != nil { - return ErrorParamsInvalid.Error(err) + return ErrorParamInvalid.Error(err) } c.h = cnf.New() @@ -99,7 +99,7 @@ func (c *componentHead) Type() string { return ComponentType } -func (c *componentHead) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentHead) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/components/http/default.go b/config/components/http/default.go index c43f719..35ac030 100644 --- a/config/components/http/default.go +++ b/config/components/http/default.go @@ -32,7 +32,7 @@ import ( libcfg "github.com/nabbar/golib/config" cpttls "github.com/nabbar/golib/config/components/tls" - libsts "github.com/nabbar/golib/status" + libsts "github.com/nabbar/golib/status/config" spfcbr "github.com/spf13/cobra" spfvbr "github.com/spf13/viper" ) diff --git a/config/components/http/errors.go b/config/components/http/errors.go index f8804ab..465723f 100644 --- a/config/components/http/errors.go +++ b/config/components/http/errors.go @@ -27,13 +27,15 @@ package http import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentHttp - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentHttp + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorStartComponent @@ -43,21 +45,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/http")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -73,5 +71,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot retrieve Logger Component" } - return "" + return liberr.NullMessage } diff --git a/config/components/http/model.go b/config/components/http/model.go index beca361..05487c8 100644 --- a/config/components/http/model.go +++ b/config/components/http/model.go @@ -44,6 +44,7 @@ type componentHttp struct { ctx libcfg.FuncContext get libcfg.FuncComponentGet vpr libcfg.FuncComponentViper + sts libcfg.FuncRouteStatus key string fsa func(cpt libcfg.Component) liberr.Error @@ -106,7 +107,7 @@ func (c *componentHttp) _getPoolServerConfig(getCfg libcfg.FuncComponentConfigGe } if err := getCfg(c.key, &cnf); err != nil { - return cnf, ErrorParamsInvalid.Error(err) + return cnf, ErrorParamInvalid.Error(err) } if tls, err := c._GetTLS(); err != nil { @@ -189,6 +190,10 @@ func (c *componentHttp) _runCli(getCfg libcfg.FuncComponentConfigGet) liberr.Err } }) + if c.sts != nil { + c.pool.StatusRoute(c.key, c.sts()) + } + if err = c.pool.ListenMultiHandler(c.hand); err != nil { return ErrorStartComponent.Error(err) } @@ -218,7 +223,7 @@ func (c *componentHttp) Type() string { return ComponentType } -func (c *componentHttp) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentHttp) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() @@ -226,6 +231,7 @@ func (c *componentHttp) Init(key string, ctx libcfg.FuncContext, get libcfg.Func c.ctx = ctx c.get = get c.vpr = vpr + c.sts = sts } func (c *componentHttp) RegisterFuncStart(before, after func(cpt libcfg.Component) liberr.Error) { diff --git a/config/components/ldap/errors.go b/config/components/ldap/errors.go index 29834b9..a0af48c 100644 --- a/config/components/ldap/errors.go +++ b/config/components/ldap/errors.go @@ -27,34 +27,32 @@ package ldap import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentRequest - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentRequest + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorDependencyTLSDefault ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/ldap")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -64,5 +62,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot retrieve TLS component" } - return "" + return liberr.NullMessage } diff --git a/config/components/ldap/interface.go b/config/components/ldap/interface.go index 11b2570..1ccfdc3 100644 --- a/config/components/ldap/interface.go +++ b/config/components/ldap/interface.go @@ -29,9 +29,8 @@ package ldap import ( "sync" - lbldap "github.com/nabbar/golib/ldap" - libcfg "github.com/nabbar/golib/config" + lbldap "github.com/nabbar/golib/ldap" ) const ( diff --git a/config/components/ldap/model.go b/config/components/ldap/model.go index d895a7c..769c6c5 100644 --- a/config/components/ldap/model.go +++ b/config/components/ldap/model.go @@ -39,6 +39,7 @@ type componentLDAP struct { ctx libcfg.FuncContext get libcfg.FuncComponentGet vpr libcfg.FuncComponentViper + sts libcfg.FuncRouteStatus key string fsa func(cpt libcfg.Component) liberr.Error @@ -93,7 +94,7 @@ func (c *componentLDAP) _runCli(ctx context.Context, getCfg libcfg.FuncComponent cfg := lbldap.Config{} if err := getCfg(c.key, &cfg); err != nil { - return ErrorParamsInvalid.Error(err) + return ErrorParamInvalid.Error(err) } if l, e := lbldap.NewLDAP(ctx, &cfg, nil); e != nil { @@ -103,6 +104,12 @@ func (c *componentLDAP) _runCli(ctx context.Context, getCfg libcfg.FuncComponent c.c = &cfg } + if c.sts != nil { + if s := c.sts(); s != nil { + + } + } + return nil } @@ -124,7 +131,7 @@ func (c *componentLDAP) Type() string { return ComponentType } -func (c *componentLDAP) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentLDAP) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/components/log/default.go b/config/components/log/default.go index e2641c7..90756fa 100644 --- a/config/components/log/default.go +++ b/config/components/log/default.go @@ -137,7 +137,7 @@ func (c *componentLog) _GetOptions(getCfg libcfg.FuncComponentConfigGet) (*liblo ) if err = getCfg(c.key, &cfg); err != nil { - return nil, ErrorParamsInvalid.Error(err) + return nil, ErrorParamInvalid.Error(err) } if val := vpr.GetBool(c.key + "disableStandard"); val { diff --git a/config/components/log/errors.go b/config/components/log/errors.go index ae48165..e2dd4f2 100644 --- a/config/components/log/errors.go +++ b/config/components/log/errors.go @@ -27,13 +27,15 @@ package log import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentLog - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentLog + ErrorParamInvalid ErrorConfigInvalid ErrorComponentNotInitialized ErrorStartLog @@ -41,21 +43,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/log")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorConfigInvalid: return "server invalid config" @@ -67,5 +65,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot update Logger with new config" } - return "" + return liberr.NullMessage } diff --git a/config/components/log/model.go b/config/components/log/model.go index e1b5e1c..b86da0f 100644 --- a/config/components/log/model.go +++ b/config/components/log/model.go @@ -115,7 +115,7 @@ func (c *componentLog) Type() string { return ComponentType } -func (c *componentLog) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentLog) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/components/mail/default.go b/config/components/mail/default.go index 1519c23..d38259e 100644 --- a/config/components/mail/default.go +++ b/config/components/mail/default.go @@ -157,7 +157,7 @@ func (c *componentMail) _getConfig(getCfg libcfg.FuncComponentConfigGet) (libmai } if e := getCfg(c.key, &cfg); e != nil { - return cfg, ErrorParamsInvalid.Error(e) + return cfg, ErrorParamInvalid.Error(e) } if val := vpr.GetString(c.key + ".charset"); val != "" { diff --git a/config/components/mail/errors.go b/config/components/mail/errors.go index b48016d..7115687 100644 --- a/config/components/mail/errors.go +++ b/config/components/mail/errors.go @@ -27,13 +27,15 @@ package mail import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentMail - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentMail + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorStartComponent @@ -43,21 +45,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/mail")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -73,5 +71,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot retrieve Logger Component" } - return "" + return liberr.NullMessage } diff --git a/config/components/mail/model.go b/config/components/mail/model.go index 752637a..76eada7 100644 --- a/config/components/mail/model.go +++ b/config/components/mail/model.go @@ -115,7 +115,7 @@ func (c *componentMail) Type() string { return ComponentType } -func (c *componentMail) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentMail) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/components/natsServer/default.go b/config/components/natsServer/default.go index e95bac7..49beb66 100644 --- a/config/components/natsServer/default.go +++ b/config/components/natsServer/default.go @@ -305,7 +305,7 @@ func (c *componentNats) _getConfig(getCfg libcfg.FuncComponentConfigGet) (libnat ) if e := getCfg(c.key, &cfg); e != nil { - return cfg, ErrorParamsInvalid.Error(e) + return cfg, ErrorParamInvalid.Error(e) } if err = cfg.Validate(); err != nil { diff --git a/config/components/natsServer/errors.go b/config/components/natsServer/errors.go index e3d4c3a..a7ba660 100644 --- a/config/components/natsServer/errors.go +++ b/config/components/natsServer/errors.go @@ -27,13 +27,15 @@ package natsServer import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentNats - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentNats + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorStartComponent @@ -43,21 +45,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/natsServer")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -73,5 +71,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot retrieve Logger Component" } - return "" + return liberr.NullMessage } diff --git a/config/components/natsServer/interface.go b/config/components/natsServer/interface.go index 9bad9b7..4d40f3a 100644 --- a/config/components/natsServer/interface.go +++ b/config/components/natsServer/interface.go @@ -29,11 +29,10 @@ package natsServer import ( "sync" - libsts "github.com/nabbar/golib/status" - libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" libnat "github.com/nabbar/golib/nats" + libsts "github.com/nabbar/golib/status" ) const ( diff --git a/config/components/natsServer/model.go b/config/components/natsServer/model.go index 6caa264..b3a5b12 100644 --- a/config/components/natsServer/model.go +++ b/config/components/natsServer/model.go @@ -151,7 +151,7 @@ func (c *componentNats) Type() string { return ComponentType } -func (c *componentNats) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentNats) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/components/nutsdb/default.go b/config/components/nutsdb/default.go index c845d49..cf483b9 100644 --- a/config/components/nutsdb/default.go +++ b/config/components/nutsdb/default.go @@ -142,7 +142,7 @@ func (c *componentNutsDB) _getConfig(getCfg libcfg.FuncComponentConfigGet) (libn ) if e := getCfg(c.key, &cfg); e != nil { - return cfg, ErrorParamsInvalid.Error(e) + return cfg, ErrorParamInvalid.Error(e) } if err = cfg.Validate(); err != nil { diff --git a/config/components/nutsdb/errors.go b/config/components/nutsdb/errors.go index 6ff56db..02794d1 100644 --- a/config/components/nutsdb/errors.go +++ b/config/components/nutsdb/errors.go @@ -27,13 +27,15 @@ package nutsdb import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentNutsDB - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentNutsDB + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorStartComponent @@ -42,21 +44,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/nutsdb")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -70,5 +68,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot retrieve default Logger" } - return "" + return liberr.NullMessage } diff --git a/config/components/nutsdb/interface.go b/config/components/nutsdb/interface.go index d3d34a9..4f3d49e 100644 --- a/config/components/nutsdb/interface.go +++ b/config/components/nutsdb/interface.go @@ -30,13 +30,11 @@ import ( "sync" "time" - libsts "github.com/nabbar/golib/status" - - cptlog "github.com/nabbar/golib/config/components/log" - libcfg "github.com/nabbar/golib/config" + cptlog "github.com/nabbar/golib/config/components/log" liberr "github.com/nabbar/golib/errors" libndb "github.com/nabbar/golib/nutsdb" + libsts "github.com/nabbar/golib/status" ) const ( diff --git a/config/components/nutsdb/model.go b/config/components/nutsdb/model.go index d5ad392..9c33b2d 100644 --- a/config/components/nutsdb/model.go +++ b/config/components/nutsdb/model.go @@ -153,7 +153,7 @@ func (c *componentNutsDB) Type() string { return ComponentType } -func (c *componentNutsDB) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentNutsDB) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/components/request/default.go b/config/components/request/default.go index d3a12d4..81ee6cf 100644 --- a/config/components/request/default.go +++ b/config/components/request/default.go @@ -32,7 +32,7 @@ import ( libcfg "github.com/nabbar/golib/config" cmptls "github.com/nabbar/golib/config/components/tls" - libsts "github.com/nabbar/golib/status" + libsts "github.com/nabbar/golib/status/config" spfcbr "github.com/spf13/cobra" spfvbr "github.com/spf13/viper" ) diff --git a/config/components/request/errors.go b/config/components/request/errors.go index 2b20d0e..d335599 100644 --- a/config/components/request/errors.go +++ b/config/components/request/errors.go @@ -27,34 +27,32 @@ package request import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentRequest - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentRequest + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorDependencyTLSDefault ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/request")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -64,5 +62,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot retrieve TLS component" } - return "" + return liberr.NullMessage } diff --git a/config/components/request/model.go b/config/components/request/model.go index dc54df3..7d291d7 100644 --- a/config/components/request/model.go +++ b/config/components/request/model.go @@ -41,6 +41,7 @@ type componentRequest struct { ctx libcfg.FuncContext get libcfg.FuncComponentGet vpr libcfg.FuncComponentViper + sts libcfg.FuncRouteStatus key string fsa func(cpt libcfg.Component) liberr.Error @@ -112,7 +113,7 @@ func (c *componentRequest) _runCli(getCfg libcfg.FuncComponentConfigGet) liberr. cfg.SetDefaultTLS(c._GetTLS) if err := getCfg(c.key, &cfg); err != nil { - return ErrorParamsInvalid.Error(err) + return ErrorParamInvalid.Error(err) } if c.r == nil { @@ -129,6 +130,12 @@ func (c *componentRequest) _runCli(getCfg libcfg.FuncComponentConfigGet) liberr. } } + if c.sts != nil { + if s := c.sts(); s != nil { + c.r.StatusRegister(s, c.key) + } + } + return nil } @@ -150,7 +157,7 @@ func (c *componentRequest) Type() string { return ComponentType } -func (c *componentRequest) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentRequest) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() @@ -158,6 +165,7 @@ func (c *componentRequest) Init(key string, ctx libcfg.FuncContext, get libcfg.F c.ctx = ctx c.get = get c.vpr = vpr + c.sts = sts } func (c *componentRequest) RegisterFuncStart(before, after func(cpt libcfg.Component) liberr.Error) { diff --git a/config/components/smtp/default.go b/config/components/smtp/default.go index 59e1550..7a08272 100644 --- a/config/components/smtp/default.go +++ b/config/components/smtp/default.go @@ -35,7 +35,7 @@ import ( cpttls "github.com/nabbar/golib/config/components/tls" liberr "github.com/nabbar/golib/errors" libsmtp "github.com/nabbar/golib/smtp" - libsts "github.com/nabbar/golib/status" + libsts "github.com/nabbar/golib/status/config" spfcbr "github.com/spf13/cobra" spfvbr "github.com/spf13/viper" ) @@ -81,7 +81,7 @@ func (c *componentSmtp) _getConfig(getCfg libcfg.FuncComponentConfigGet) (libsmt ) if e := getCfg(c.key, &cfg); e != nil { - return cfg, ErrorParamsInvalid.Error(e) + return cfg, ErrorParamInvalid.Error(e) } if val := vpr.GetString(c.key + "dsn"); val != "" { diff --git a/config/components/smtp/errors.go b/config/components/smtp/errors.go index d00433c..f37d3a1 100644 --- a/config/components/smtp/errors.go +++ b/config/components/smtp/errors.go @@ -27,13 +27,15 @@ package smtp import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentSmtp - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentSmtp + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorStartComponent @@ -43,21 +45,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/smtp")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -73,5 +71,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot retrieve Logger Component" } - return "" + return liberr.NullMessage } diff --git a/config/components/smtp/interface.go b/config/components/smtp/interface.go index 042d026..77f3a19 100644 --- a/config/components/smtp/interface.go +++ b/config/components/smtp/interface.go @@ -29,13 +29,11 @@ package smtp import ( "sync" - libsts "github.com/nabbar/golib/status" - - cpttls "github.com/nabbar/golib/config/components/tls" - libcfg "github.com/nabbar/golib/config" + cpttls "github.com/nabbar/golib/config/components/tls" liberr "github.com/nabbar/golib/errors" libsmtp "github.com/nabbar/golib/smtp" + libsts "github.com/nabbar/golib/status" ) const ( diff --git a/config/components/smtp/model.go b/config/components/smtp/model.go index 5673314..a29883c 100644 --- a/config/components/smtp/model.go +++ b/config/components/smtp/model.go @@ -141,7 +141,7 @@ func (c *componentSmtp) Type() string { return ComponentType } -func (c *componentSmtp) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentSmtp) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/components/tls/default.go b/config/components/tls/default.go index 1b88f92..f74ddd3 100644 --- a/config/components/tls/default.go +++ b/config/components/tls/default.go @@ -119,7 +119,7 @@ func (c *componentTls) _getConfig(getCfg libcfg.FuncComponentConfigGet) (*libtls cfg := libtls.Config{} if err := getCfg(c.key, &cfg); err != nil { - return nil, ErrorParamsInvalid.Error(err) + return nil, ErrorParamInvalid.Error(err) } if err := cfg.Validate(); err != nil { diff --git a/config/components/tls/errors.go b/config/components/tls/errors.go index 1b366a8..019b6e3 100644 --- a/config/components/tls/errors.go +++ b/config/components/tls/errors.go @@ -27,13 +27,15 @@ package tls import ( + "fmt" + libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + libcfg.MinErrorComponentTls - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + libcfg.MinErrorComponentTls + ErrorParamInvalid ErrorComponentNotInitialized ErrorConfigInvalid ErrorComponentStart @@ -41,21 +43,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config/components/tls")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorComponentNotInitialized: return "this component seems to not be correctly initialized" @@ -67,5 +65,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot update database connection with new config" } - return "" + return liberr.NullMessage } diff --git a/config/components/tls/model.go b/config/components/tls/model.go index 811d13d..596950d 100644 --- a/config/components/tls/model.go +++ b/config/components/tls/model.go @@ -112,7 +112,7 @@ func (c *componentTls) Type() string { return ComponentType } -func (c *componentTls) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper) { +func (c *componentTls) Init(key string, ctx libcfg.FuncContext, get libcfg.FuncComponentGet, vpr libcfg.FuncComponentViper, sts libcfg.FuncRouteStatus) { c.m.Lock() defer c.m.Unlock() diff --git a/config/cptList.go b/config/cptList.go index 1211273..5b04a66 100644 --- a/config/cptList.go +++ b/config/cptList.go @@ -35,10 +35,11 @@ import ( "sync/atomic" "time" - spfcbr "github.com/spf13/cobra" - spfvpr "github.com/spf13/viper" + "golang.org/x/exp/slices" liberr "github.com/nabbar/golib/errors" + spfcbr "github.com/spf13/cobra" + spfvpr "github.com/spf13/viper" ) const JSONIndent = " " @@ -280,7 +281,7 @@ func (c *componentList) reloadOne(isReload []string, key string, getCfg FuncComp return isReload, ErrorComponentNotFound.ErrorParent(fmt.Errorf("component: %s", key)) } else if cpt = c.ComponentGet(key); cpt == nil { return isReload, ErrorComponentNotFound.ErrorParent(fmt.Errorf("component: %s", key)) - } else if stringIsInSlice(isReload, key) { + } else if slices.Contains(isReload, key) { return isReload, nil } @@ -370,12 +371,18 @@ func (c *componentList) DefaultConfig() io.Reader { buffer.WriteString("\n") buffer.WriteString("}") - var res = bytes.NewBuffer(make([]byte, 0)) - if err := json.Indent(res, buffer.Bytes(), "", JSONIndent); err != nil { + var ( + cmp = bytes.NewBuffer(make([]byte, 0)) + ind = bytes.NewBuffer(make([]byte, 0)) + ) + + if err := json.Compact(cmp, buffer.Bytes()); err != nil { + return buffer + } else if err = json.Indent(ind, cmp.Bytes(), "", JSONIndent); err != nil { return buffer } - return res + return ind } func (c *componentList) RegisterFlag(Command *spfcbr.Command, Viper *spfvpr.Viper) error { diff --git a/config/errors.go b/config/errors.go index 634a600..46e8c2c 100644 --- a/config/errors.go +++ b/config/errors.go @@ -26,10 +26,14 @@ package config -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgConfig + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgConfig ErrorConfigMissingViper ErrorComponentNotFound ErrorComponentFlagError @@ -40,7 +44,7 @@ const ( ) const ( - MinErrorComponentAws = ErrorParamsEmpty + 10 + MinErrorComponentAws = ErrorParamEmpty + 10 MinErrorComponentDatabase = MinErrorComponentAws + 10 MinErrorComponentHead = MinErrorComponentDatabase + 10 MinErrorComponentHttp = MinErrorComponentHead + 10 @@ -53,22 +57,18 @@ const ( MinErrorComponentTls = MinErrorComponentSmtp + 10 ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/config")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: + case liberr.UNK_ERROR: return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorConfigMissingViper: return "missing valid viper function" @@ -86,5 +86,5 @@ func getMessage(code errors.CodeError) (message string) { return "cannot reload at least one component" } - return "" + return liberr.NullMessage } diff --git a/config/interface.go b/config/interface.go index 7ca2f6f..ba332a0 100644 --- a/config/interface.go +++ b/config/interface.go @@ -33,14 +33,15 @@ import ( "sync" "syscall" - spfvpr "github.com/spf13/viper" - libctx "github.com/nabbar/golib/context" liberr "github.com/nabbar/golib/errors" + libsts "github.com/nabbar/golib/status" libvpr "github.com/nabbar/golib/viper" + spfvpr "github.com/spf13/viper" ) type FuncContext func() context.Context +type FuncRouteStatus func() libsts.RouteStatus type FuncComponentGet func(key string) Component type FuncComponentViper func() *spfvpr.Viper type FuncComponentConfigGet func(key string, model interface{}) liberr.Error @@ -74,8 +75,14 @@ type Config interface { // Section Event : github.com/nabbar/golib/config */ + // RegisterFuncViper is used to expose golib Viper instance to all config component. + // With this function, the component can load his own config part and start or reload. RegisterFuncViper(fct func() libvpr.Viper) + // RegisterFuncRouteStatus is used to expose golib Status Router instance to all config component. + // With this function, the component can register component status for router status and expose his own health. + RegisterFuncRouteStatus(fct FuncRouteStatus) + // 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. diff --git a/config/model.go b/config/model.go index f5064e9..2aa4395 100644 --- a/config/model.go +++ b/config/model.go @@ -29,16 +29,15 @@ package config import ( "context" "fmt" + "io" "os" + "sync" libctx "github.com/nabbar/golib/context" liberr "github.com/nabbar/golib/errors" libvpr "github.com/nabbar/golib/viper" spfcbr "github.com/spf13/cobra" spfvpr "github.com/spf13/viper" - - "io" - "sync" ) type configModel struct { @@ -49,6 +48,7 @@ type configModel struct { cpt ComponentList + fctGolibStatus FuncRouteStatus fctGolibViper func() libvpr.Viper fctStartBefore func() liberr.Error fctStartAfter func() liberr.Error @@ -123,6 +123,10 @@ func (c *configModel) RegisterFuncViper(fct func() libvpr.Viper) { c.fctGolibViper = fct } +func (c *configModel) RegisterFuncRouteStatus(fct FuncRouteStatus) { + c.fctGolibStatus = fct +} + func (c *configModel) Start() liberr.Error { c.m.Lock() defer c.m.Unlock() @@ -250,7 +254,7 @@ func (c *configModel) ComponentDel(key string) { } func (c *configModel) ComponentSet(key string, cpt Component) { - cpt.Init(key, c.Context, c.ComponentGet, func() *spfvpr.Viper { + fv := func() *spfvpr.Viper { if c.fctGolibViper == nil { return nil } else if vpr := c.fctGolibViper(); vpr == nil { @@ -258,8 +262,9 @@ func (c *configModel) ComponentSet(key string, cpt Component) { } else { return vpr.Viper() } - }) + } + cpt.Init(key, c.Context, c.ComponentGet, fv, c.fctGolibStatus) c.cpt.ComponentSet(key, cpt) } diff --git a/console/error.go b/console/error.go index 1b44624..580ab9d 100644 --- a/console/error.go +++ b/console/error.go @@ -26,31 +26,29 @@ package console -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgConsole + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgConsole ErrorColorIOFprintf ErrorColorBufWrite ErrorColorBufUndefined ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/console")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorColorIOFprintf: return "cannot write on IO" @@ -60,5 +58,5 @@ func getMessage(code errors.CodeError) (message string) { return "buffer is not defined" } - return "" + return liberr.NullMessage } diff --git a/database/config.go b/database/config.go index 6a01c81..8af5312 100644 --- a/database/config.go +++ b/database/config.go @@ -32,7 +32,7 @@ import ( "fmt" "time" - libsts "github.com/nabbar/golib/status" + libsts "github.com/nabbar/golib/status/config" libval "github.com/go-playground/validator/v10" liberr "github.com/nabbar/golib/errors" diff --git a/errors/code.go b/errors/code.go index 42d6f47..d3bccf6 100644 --- a/errors/code.go +++ b/errors/code.go @@ -40,8 +40,11 @@ type Message func(code CodeError) (message string) type CodeError uint16 const UNK_ERROR CodeError = 0 +const UnknownError CodeError = 0 const UNK_MESSAGE = "unknown error" +const UnknownMessage = "unknown error" const NUL_MESSAGE = "" +const NullMessage = "" func (c CodeError) GetUint16() uint16 { return uint16(c) @@ -56,8 +59,8 @@ func (c CodeError) GetString() string { } func (c CodeError) GetMessage() string { - if c == UNK_ERROR { - return UNK_MESSAGE + if c == UnknownError { + return UnknownMessage } if f, ok := idMsgFct[findCodeErrorInMapMessage(c)]; ok { @@ -66,7 +69,7 @@ func (c CodeError) GetMessage() string { } } - return UNK_MESSAGE + return UnknownMessage } func (c CodeError) Error(p Error) Error { @@ -125,7 +128,7 @@ func RegisterIdFctMessage(minCode CodeError, fct Message) { func ExistInMapMessage(code CodeError) bool { if f, ok := idMsgFct[findCodeErrorInMapMessage(code)]; ok { - if m := f(code); m != NUL_MESSAGE { + if m := f(code); m != NullMessage { return true } } diff --git a/go.mod b/go.mod index ed060e5..23422af 100644 --- a/go.mod +++ b/go.mod @@ -1,58 +1,59 @@ module github.com/nabbar/golib -go 1.18 +go 1.19 require ( - github.com/aws/aws-sdk-go-v2 v1.16.8 - github.com/aws/aws-sdk-go-v2/config v1.15.15 - github.com/aws/aws-sdk-go-v2/credentials v1.12.10 - github.com/aws/aws-sdk-go-v2/service/iam v1.18.10 - github.com/aws/aws-sdk-go-v2/service/s3 v1.27.2 - github.com/bits-and-blooms/bitset v1.3.0 + github.com/aws/aws-sdk-go-v2 v1.16.14 + github.com/aws/aws-sdk-go-v2/config v1.17.5 + github.com/aws/aws-sdk-go-v2/credentials v1.12.18 + github.com/aws/aws-sdk-go-v2/service/iam v1.18.17 + github.com/aws/aws-sdk-go-v2/service/s3 v1.27.9 + github.com/bits-and-blooms/bitset v1.3.2 github.com/c-bata/go-prompt v0.2.6 github.com/fatih/color v1.13.0 github.com/fsnotify/fsnotify v1.5.4 github.com/fxamacker/cbor/v2 v2.4.0 github.com/gin-gonic/gin v1.8.1 github.com/go-ldap/ldap/v3 v3.4.4 - github.com/go-playground/validator/v10 v10.10.0 + github.com/go-playground/validator/v10 v10.11.0 github.com/google/go-github/v33 v33.0.0 - github.com/hashicorp/go-hclog v1.2.2 + github.com/hashicorp/go-hclog v1.3.0 github.com/hashicorp/go-retryablehttp v0.7.1 github.com/hashicorp/go-uuid v1.0.3 github.com/hashicorp/go-version v1.6.0 - github.com/jlaffaye/ftp v0.0.0-20220630165035-11536801d1ff + github.com/jlaffaye/ftp v0.1.0 github.com/lni/dragonboat/v3 v3.3.5 github.com/matcornic/hermes/v2 v2.1.0 - github.com/mattn/go-colorable v0.1.12 + github.com/mattn/go-colorable v0.1.13 github.com/mitchellh/go-homedir v1.1.0 github.com/nats-io/jwt/v2 v2.3.0 - github.com/nats-io/nats-server/v2 v2.8.4 - github.com/nats-io/nats.go v1.16.0 - github.com/onsi/ginkgo/v2 v2.1.4 - github.com/onsi/gomega v1.20.0 + github.com/nats-io/nats-server/v2 v2.9.0 + github.com/nats-io/nats.go v1.16.1-0.20220906180156-a1017eec10b0 + github.com/onsi/ginkgo/v2 v2.1.6 + github.com/onsi/gomega v1.20.2 github.com/pelletier/go-toml v1.9.5 github.com/pkg/errors v0.9.1 - github.com/prometheus/client_golang v1.12.2 + github.com/prometheus/client_golang v1.13.0 github.com/shirou/gopsutil v3.21.11+incompatible github.com/sirupsen/logrus v1.9.0 github.com/spf13/cobra v1.5.0 github.com/spf13/jwalterweatherman v1.1.0 - github.com/spf13/viper v1.12.0 + github.com/spf13/viper v1.13.0 github.com/vbauerster/mpb/v5 v5.4.0 - github.com/xanzy/go-gitlab v0.70.0 + github.com/xanzy/go-gitlab v0.73.1 github.com/xhit/go-simple-mail v2.2.2+incompatible - github.com/xujiajun/nutsdb v0.9.0 - github.com/xujiajun/utils v0.0.0-20190123093513-8bf096c4f53b - golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e - golang.org/x/oauth2 v0.0.0-20220722155238-128564f6959c - golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 - golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 + github.com/xujiajun/nutsdb v0.10.0 + github.com/xujiajun/utils v0.0.0-20220904132955-5f7c5b914235 + golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 + golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48 + golang.org/x/oauth2 v0.0.0-20220909003341-f21342109be1 + golang.org/x/sync v0.0.0-20220907140024-f12130a52804 + golang.org/x/sys v0.0.0-20220909162455-aba9fc2a8ff2 golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 gopkg.in/yaml.v3 v3.0.1 gorm.io/driver/clickhouse v0.4.2 - gorm.io/driver/mysql v1.3.5 - gorm.io/driver/postgres v1.3.8 + gorm.io/driver/mysql v1.3.6 + gorm.io/driver/postgres v1.3.9 gorm.io/driver/sqlite v1.3.6 gorm.io/driver/sqlserver v1.3.2 gorm.io/gorm v1.23.8 @@ -70,19 +71,20 @@ require ( github.com/andybalholm/cascadia v1.0.0 // indirect github.com/aokoli/goutils v1.0.1 // indirect github.com/armon/go-metrics v0.3.10 // indirect - github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.3 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.9 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.15 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.9 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.3.16 // indirect - github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.6 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.3 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.10 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.9 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.9 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.11.13 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.16.10 // indirect - github.com/aws/smithy-go v1.12.0 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.7 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.15 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.21 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.15 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.3.22 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.12 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.8 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.16 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.15 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.15 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.11.21 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.13.3 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.16.17 // indirect + github.com/aws/smithy-go v1.13.2 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bwmarrin/snowflake v0.3.0 // indirect github.com/cespare/xxhash/v2 v2.1.2 // indirect @@ -98,7 +100,7 @@ require ( github.com/go-playground/locales v0.14.0 // indirect github.com/go-playground/universal-translator v0.18.0 // indirect github.com/go-sql-driver/mysql v1.6.0 // indirect - github.com/goccy/go-json v0.9.7 // indirect + github.com/goccy/go-json v0.9.11 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe // indirect github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188 // indirect @@ -134,13 +136,13 @@ require ( github.com/jinzhu/now v1.1.5 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/juju/ratelimit v1.0.2-0.20191002062651-f60b32039441 // indirect - github.com/klauspost/compress v1.14.4 // indirect + github.com/klauspost/compress v1.15.9 // indirect github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/lni/goutils v1.3.0 // indirect github.com/magiconair/properties v1.8.6 // indirect - github.com/mattn/go-isatty v0.0.14 // indirect + github.com/mattn/go-isatty v0.0.16 // indirect github.com/mattn/go-runewidth v0.0.9 // indirect github.com/mattn/go-sqlite3 v1.14.12 // indirect github.com/mattn/go-tty v0.0.3 // indirect @@ -154,12 +156,12 @@ require ( github.com/nats-io/nuid v1.0.1 // indirect github.com/olekukonko/tablewriter v0.0.1 // indirect github.com/paulmach/orb v0.7.1 // indirect - github.com/pelletier/go-toml/v2 v2.0.1 // indirect + github.com/pelletier/go-toml/v2 v2.0.5 // indirect github.com/pierrec/lz4/v4 v4.1.15 // indirect github.com/pkg/term v1.2.0-beta.2 // indirect github.com/prometheus/client_model v0.2.0 // indirect - github.com/prometheus/common v0.32.1 // indirect - github.com/prometheus/procfs v0.7.3 // indirect + github.com/prometheus/common v0.37.0 // indirect + github.com/prometheus/procfs v0.8.0 // indirect github.com/rogpeppe/go-internal v1.8.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect @@ -168,7 +170,7 @@ require ( github.com/spf13/cast v1.5.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - github.com/subosito/gotenv v1.3.0 // indirect + github.com/subosito/gotenv v1.4.1 // indirect github.com/ugorji/go/codec v1.2.7 // indirect github.com/valyala/fastrand v1.0.0 // indirect github.com/valyala/histogram v1.0.1 // indirect @@ -179,12 +181,11 @@ require ( github.com/yusufpapurcu/wmi v1.2.2 // indirect go.opentelemetry.io/otel v1.7.0 // indirect go.opentelemetry.io/otel/trace v1.7.0 // indirect - golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect - golang.org/x/exp v0.0.0-20200513190911-00229845015e // indirect + golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 // indirect golang.org/x/text v0.3.7 // indirect - golang.org/x/time v0.0.0-20220411224347-583f2d630306 // indirect + golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/protobuf v1.28.0 // indirect - gopkg.in/ini.v1 v1.66.4 // indirect + google.golang.org/protobuf v1.28.1 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/httpcli/errors.go b/httpcli/errors.go index a725e42..2f83ab4 100644 --- a/httpcli/errors.go +++ b/httpcli/errors.go @@ -27,32 +27,30 @@ package httpcli import ( + "fmt" + liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + liberr.MinPkgHttpCli - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgHttpCli + ErrorParamInvalid ErrorValidatorError ErrorClientTransportHttp2 ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/httpcli")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorValidatorError: return "config seems to be invalid" @@ -60,5 +58,5 @@ func getMessage(code liberr.CodeError) (message string) { return "error while configure http2 transport for client" } - return liberr.NUL_MESSAGE + return liberr.NullMessage } diff --git a/httpserver/config.go b/httpserver/config.go index 495b9e2..c02af8d 100644 --- a/httpserver/config.go +++ b/httpserver/config.go @@ -34,10 +34,11 @@ import ( "strings" "time" + libsts "github.com/nabbar/golib/status/config" + libval "github.com/go-playground/validator/v10" libtls "github.com/nabbar/golib/certificates" liberr "github.com/nabbar/golib/errors" - libsts "github.com/nabbar/golib/status" ) type MapUpdPoolServerConfig func(cfg ServerConfig) ServerConfig diff --git a/httpserver/error.go b/httpserver/error.go index 4692056..4889d25 100644 --- a/httpserver/error.go +++ b/httpserver/error.go @@ -26,10 +26,14 @@ package httpserver -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgHttpServer + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgHttpServer ErrorHTTP2Configure ErrorPoolAdd ErrorPoolValidate @@ -40,22 +44,16 @@ const ( ErrorServerOffline ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/httpserver")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorHTTP2Configure: return "cannot initialize http2 over http server" @@ -75,5 +73,5 @@ func getMessage(code errors.CodeError) (message string) { return "server offline" } - return "" + return liberr.NullMessage } diff --git a/httpserver/server.go b/httpserver/server.go index 21a8580..f6b06fd 100644 --- a/httpserver/server.go +++ b/httpserver/server.go @@ -34,6 +34,8 @@ import ( "sync/atomic" "time" + "github.com/nabbar/golib/status/config" + liblog "github.com/nabbar/golib/logger" liberr "github.com/nabbar/golib/errors" @@ -253,7 +255,7 @@ func (s *server) StatusHealth() error { func (s *server) StatusComponent() libsts.Component { if cfg := s.GetConfig(); cfg == nil { - cnf := libsts.ConfigStatus{ + cnf := config.ConfigStatus{ Mandatory: true, MessageOK: "", MessageKO: "", diff --git a/ioutils/error.go b/ioutils/error.go index 9f1a86d..184ba2e 100644 --- a/ioutils/error.go +++ b/ioutils/error.go @@ -26,10 +26,14 @@ package ioutils -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgIOUtils + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgIOUtils ErrorSyscallRLimitGet ErrorSyscallRLimitSet ErrorIOFileStat @@ -41,22 +45,16 @@ const ( ErrorNilPointer ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/ioutils")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorSyscallRLimitGet: return "error on retrieve value in syscall rlimit" @@ -78,5 +76,5 @@ func getMessage(code errors.CodeError) (message string) { return "cannot call function for a nil pointer" } - return "" + return liberr.NullMessage } diff --git a/ldap/error.go b/ldap/error.go index ba101ca..58ab437 100644 --- a/ldap/error.go +++ b/ldap/error.go @@ -26,10 +26,14 @@ package ldap -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorEmptyParams errors.CodeError = iota + errors.MinPkgLDAP + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgLDAP ErrorLDAPContext ErrorLDAPServerConfig ErrorLDAPServerConnection @@ -49,21 +53,16 @@ const ( ErrorLDAPGroupNotFound ) -var isCodeError = errors.ExistInMapMessage(ErrorEmptyParams) - -func IsCodeError() bool { - return isCodeError -} - func init() { - errors.RegisterIdFctMessage(ErrorEmptyParams, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/ldap")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorEmptyParams: + case ErrorParamEmpty: return "given parameters is empty" case ErrorLDAPContext: return "LDAP server connection context occurs an error" @@ -101,5 +100,5 @@ func getMessage(code errors.CodeError) (message string) { return "group not found" } - return "" + return liberr.NullMessage } diff --git a/ldap/ldap.go b/ldap/ldap.go index 57c186e..22afe79 100644 --- a/ldap/ldap.go +++ b/ldap/ldap.go @@ -57,7 +57,7 @@ type HelperLDAP struct { // NewLDAP build a new LDAP helper based on config struct given. func NewLDAP(ctx context.Context, cnf *Config, attributes []string) (*HelperLDAP, liberr.Error) { if cnf == nil { - return nil, ErrorEmptyParams.Error(nil) + return nil, ErrorParamEmpty.Error(nil) } return &HelperLDAP{ @@ -210,7 +210,7 @@ func (lc *HelperLDAP) starttls(l *ldap.Conn) liberr.Error { func (lc *HelperLDAP) tryConnect() (TLSMode, liberr.Error) { if lc == nil { - return TLSModeNone, ErrorEmptyParams.Error(nil) + return TLSModeNone, ErrorParamEmpty.Error(nil) } var ( @@ -257,7 +257,7 @@ func (lc *HelperLDAP) tryConnect() (TLSMode, liberr.Error) { func (lc *HelperLDAP) connect() liberr.Error { if lc == nil || lc.ctx == nil { - return ErrorLDAPContext.Error(ErrorEmptyParams.Error(nil)) + return ErrorLDAPContext.Error(ErrorParamEmpty.Error(nil)) } if err := lc.ctx.Err(); err != nil { @@ -320,7 +320,7 @@ func (lc *HelperLDAP) connect() liberr.Error { // Check used to check if connection success (without any bind). func (lc *HelperLDAP) Check() liberr.Error { if lc == nil { - return ErrorEmptyParams.Error(nil) + return ErrorParamEmpty.Error(nil) } if lc.conn == nil { @@ -355,7 +355,7 @@ func (lc *HelperLDAP) Close() { // AuthUser used to test bind given user uid and password. func (lc *HelperLDAP) AuthUser(username, password string) liberr.Error { if lc == nil { - return ErrorEmptyParams.Error(nil) + return ErrorParamEmpty.Error(nil) } if err := lc.connect(); err != nil { @@ -363,7 +363,7 @@ func (lc *HelperLDAP) AuthUser(username, password string) liberr.Error { } if username == "" || password == "" { - return ErrorEmptyParams.Error(nil) + return ErrorParamEmpty.Error(nil) } err := lc.conn.Bind(username, password) @@ -374,7 +374,7 @@ func (lc *HelperLDAP) AuthUser(username, password string) liberr.Error { // Connect used to connect and bind to server. func (lc *HelperLDAP) Connect() liberr.Error { if lc == nil { - return ErrorEmptyParams.Error(nil) + return ErrorParamEmpty.Error(nil) } if err := lc.AuthUser(lc.bindDN, lc.bindPass); err != nil { diff --git a/logger/error.go b/logger/error.go index ec46c82..95b76af 100644 --- a/logger/error.go +++ b/logger/error.go @@ -27,31 +27,30 @@ package logger import ( + "fmt" + liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + liberr.MinPkgLogger + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgLogger ErrorValidatorError ) -var isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - -func IsCodeError() bool { - return isCodeError -} - func init() { - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/logger")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorValidatorError: return "logger : invalid config" } - return liberr.UNK_MESSAGE + return liberr.NullMessage } diff --git a/logger/hclog.go b/logger/hclog.go index b5b92f4..5bf7520 100644 --- a/logger/hclog.go +++ b/logger/hclog.go @@ -45,7 +45,7 @@ type _hclog struct { func (l *_hclog) Log(level hclog.Level, msg string, args ...interface{}) { switch level { - case hclog.Off, hclog.NoLevel: + case hclog.NoLevel, hclog.Off: return case hclog.Trace: l.l.Debug(msg, nil, args...) @@ -141,7 +141,7 @@ func (l *_hclog) ResetNamed(name string) hclog.Logger { func (l *_hclog) SetLevel(level hclog.Level) { switch level { - case hclog.Off, hclog.NoLevel: + case hclog.NoLevel, hclog.Off: l.l.SetLevel(NilLevel) case hclog.Trace: l.l.SetLevel(DebugLevel) @@ -159,7 +159,7 @@ func (l *_hclog) SetLevel(level hclog.Level) { func (l *_hclog) StandardLogger(opts *hclog.StandardLoggerOptions) *log.Logger { var lvl Level switch opts.ForceLevel { - case hclog.Off, hclog.NoLevel: + case hclog.NoLevel, hclog.Off: lvl = NilLevel case hclog.Trace: lvl = DebugLevel diff --git a/mail/email.go b/mail/email.go index 91553bc..6387610 100644 --- a/mail/email.go +++ b/mail/email.go @@ -25,6 +25,8 @@ package mail +import "golang.org/x/exp/slices" + const ( headerFrom = "From" headerSender = "Sender" @@ -150,35 +152,21 @@ func (e *email) AddRecipients(rt recipientType, rcpt ...string) { for _, s := range rcpt { switch rt { case RecipientTo: - if !e.isInSlice(e.to, s) { + if !slices.Contains(e.to, s) { e.to = append(e.to, s) } case RecipientCC: - if !e.isInSlice(e.cc, s) { + if !slices.Contains(e.cc, s) { e.cc = append(e.cc, s) } case RecipientBCC: - if !e.isInSlice(e.bcc, s) { + if !slices.Contains(e.bcc, s) { e.bcc = append(e.bcc, s) } } } } -func (e email) isInSlice(s []string, str string) bool { - if str == "" { - return true - } - - for _, i := range s { - if i == str { - return true - } - } - - return false -} - func (e *email) getHeader(h func(key string, values ...string)) { h(headerFrom, e.GetFrom()) h(headerSender, e.GetSender()) diff --git a/mail/error.go b/mail/error.go index 7c96951..4b7bbc1 100644 --- a/mail/error.go +++ b/mail/error.go @@ -26,10 +26,14 @@ package mail -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgMail + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgMail ErrorMailConfigInvalid ErrorMailIORead ErrorMailIOWrite @@ -38,22 +42,16 @@ const ( ErrorMailSenderInit ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/mail")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorMailConfigInvalid: return "config is invalid" @@ -69,5 +67,5 @@ func getMessage(code errors.CodeError) (message string) { return "error occurs while to preparing SMTP Email sender" } - return "" + return liberr.NullMessage } diff --git a/mail/sender.go b/mail/sender.go index 6e4dfd7..86da666 100644 --- a/mail/sender.go +++ b/mail/sender.go @@ -244,10 +244,10 @@ func (s *sender) Send(ctx context.Context, cli libsmtp.SMTP) liberr.Error { if len(s.from) < _MinSizeAddr { //nolint #goerr113 - return ErrorParamsEmpty.ErrorParent(fmt.Errorf("parameters 'from' is not valid")) + return ErrorParamEmpty.ErrorParent(fmt.Errorf("parameters 'from' is not valid")) } else if len(s.rcpt) < 1 || len(s.rcpt[0]) < _MinSizeAddr { //nolint #goerr113 - return ErrorParamsEmpty.ErrorParent(fmt.Errorf("parameters 'receipient' is not valid")) + return ErrorParamEmpty.ErrorParent(fmt.Errorf("parameters 'receipient' is not valid")) } e := cli.Send(ctx, s.from, s.rcpt, s.data) diff --git a/mailPooler/error.go b/mailPooler/error.go index fc06880..4d14551 100644 --- a/mailPooler/error.go +++ b/mailPooler/error.go @@ -25,30 +25,28 @@ package mailPooler -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgMailPooler + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgMailPooler ErrorMailPooler ErrorMailPoolerContext ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/mailPooler")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorMailPooler: return "generic mail pooler error" @@ -56,5 +54,5 @@ func getMessage(code errors.CodeError) (message string) { return "context has trigger error" } - return "" + return liberr.NullMessage } diff --git a/mailPooler/model.go b/mailPooler/model.go index 8d1a71f..f0b2a74 100644 --- a/mailPooler/model.go +++ b/mailPooler/model.go @@ -45,7 +45,7 @@ type pooler struct { func (p *pooler) Reset() liberr.Error { if p.s == nil { - return ErrorParamsEmpty.ErrorParent(errors.New("smtp client is not define")) + return ErrorParamEmpty.ErrorParent(errors.New("smtp client is not define")) } if err := p.c.Reset(); err != nil { @@ -71,7 +71,7 @@ func (p *pooler) NewPooler() Pooler { func (p *pooler) Send(ctx context.Context, from string, to []string, data io.WriterTo) liberr.Error { if p.s == nil { - return ErrorParamsEmpty.ErrorParent(errors.New("smtp client is not define")) + return ErrorParamEmpty.ErrorParent(errors.New("smtp client is not define")) } if err := p.c.Pool(ctx); err != nil { @@ -83,7 +83,7 @@ func (p *pooler) Send(ctx context.Context, from string, to []string, data io.Wri func (p *pooler) Client(ctx context.Context) (*smtp.Client, liberr.Error) { if p.s == nil { - return nil, ErrorParamsEmpty.ErrorParent(errors.New("smtp client is not define")) + return nil, ErrorParamEmpty.ErrorParent(errors.New("smtp client is not define")) } return p.s.Client(ctx) @@ -97,7 +97,7 @@ func (p *pooler) Close() { func (p *pooler) Check(ctx context.Context) liberr.Error { if p.s == nil { - return ErrorParamsEmpty.ErrorParent(errors.New("smtp client is not define")) + return ErrorParamEmpty.ErrorParent(errors.New("smtp client is not define")) } return p.s.Check(ctx) @@ -121,7 +121,7 @@ func (p *pooler) StatusInfo() (name string, release string, hash string) { func (p *pooler) StatusHealth() error { if p.s == nil { - return ErrorParamsEmpty.ErrorParent(errors.New("smtp client is not define")) + return ErrorParamEmpty.ErrorParent(errors.New("smtp client is not define")) } return p.s.StatusHealth() diff --git a/mailer/error.go b/mailer/error.go index d73c397..5fb21eb 100644 --- a/mailer/error.go +++ b/mailer/error.go @@ -26,31 +26,29 @@ package mailer -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgMailer + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgMailer ErrorMailerConfigInvalid ErrorMailerHtml ErrorMailerText ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/mailer")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorMailerConfigInvalid: return "config of mailer is invalid" @@ -60,5 +58,5 @@ func getMessage(code errors.CodeError) (message string) { return "cannot generate pain text content" } - return "" + return liberr.NullMessage } diff --git a/nats/config.go b/nats/config.go index 4eec6c5..97057ca 100644 --- a/nats/config.go +++ b/nats/config.go @@ -36,12 +36,13 @@ import ( "strings" "time" + libsts "github.com/nabbar/golib/status/config" + libval "github.com/go-playground/validator/v10" libtls "github.com/nabbar/golib/certificates" liberr "github.com/nabbar/golib/errors" libiot "github.com/nabbar/golib/ioutils" liblog "github.com/nabbar/golib/logger" - libsts "github.com/nabbar/golib/status" natjwt "github.com/nats-io/jwt/v2" natsrv "github.com/nats-io/nats-server/v2/server" ) diff --git a/nats/server.go b/nats/server.go index 409651d..2427194 100644 --- a/nats/server.go +++ b/nats/server.go @@ -36,6 +36,8 @@ import ( "sync/atomic" "time" + "github.com/nabbar/golib/status/config" + libtls "github.com/nabbar/golib/certificates" liberr "github.com/nabbar/golib/errors" libsts "github.com/nabbar/golib/status" @@ -70,7 +72,7 @@ type Server interface { StatusRouter(sts libsts.RouteStatus, prefix string) } -func NewServer(opt *natsrv.Options, sts libsts.ConfigStatus) Server { +func NewServer(opt *natsrv.Options, sts config.ConfigStatus) Server { o := new(atomic.Value) if opt != nil { @@ -86,7 +88,7 @@ func NewServer(opt *natsrv.Options, sts libsts.ConfigStatus) Server { } type server struct { - c *libsts.ConfigStatus + c *config.ConfigStatus o *atomic.Value s *atomic.Value r *atomic.Value diff --git a/nutsdb/config.go b/nutsdb/config.go index 57dc628..5c8f143 100644 --- a/nutsdb/config.go +++ b/nutsdb/config.go @@ -36,7 +36,7 @@ import ( libval "github.com/go-playground/validator/v10" libclu "github.com/nabbar/golib/cluster" liberr "github.com/nabbar/golib/errors" - libsts "github.com/nabbar/golib/status" + libsts "github.com/nabbar/golib/status/config" "github.com/xujiajun/nutsdb" ) diff --git a/nutsdb/errors.go b/nutsdb/errors.go index 6d4cae1..1775a97 100644 --- a/nutsdb/errors.go +++ b/nutsdb/errors.go @@ -30,7 +30,9 @@ package nutsdb -import liberr "github.com/nabbar/golib/errors" +import ( + liberr "github.com/nabbar/golib/errors" +) const ( ErrorParamsEmpty liberr.CodeError = iota + liberr.MinPkgNutsDB diff --git a/progress/error.go b/progress/error.go index 66d406e..b757176 100644 --- a/progress/error.go +++ b/progress/error.go @@ -27,39 +27,37 @@ package progress -import liberr "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty liberr.CodeError = iota + liberr.MinPkgNutsDB - ErrorParamsMissing - ErrorParamsMismatching + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgNutsDB + ErrorParamMissing + ErrorParamMismatching ErrorBarNotInitialized ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/progress")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case liberr.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least on given parameters is empty" - case ErrorParamsMissing: + case ErrorParamMissing: return "at least on given parameters is missing" - case ErrorParamsMismatching: + case ErrorParamMismatching: return "at least on given parameters is mismatching awaiting type" case ErrorBarNotInitialized: return "progress bar not initialized" } - return "" + return liberr.NullMessage } diff --git a/request/errors.go b/request/errors.go index 2fa6ebc..28f79cd 100644 --- a/request/errors.go +++ b/request/errors.go @@ -27,12 +27,14 @@ package request import ( + "fmt" + liberr "github.com/nabbar/golib/errors" ) const ( - ErrorParamsEmpty liberr.CodeError = iota + liberr.MinPkgRequest - ErrorParamsInvalid + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgRequest + ErrorParamInvalid ErrorValidatorError ErrorCreateRequest ErrorSendRequest @@ -45,21 +47,17 @@ const ( ) func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamsEmpty) - liberr.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) -} - -var isCodeError = false - -func IsCodeError() bool { - return isCodeError + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/request")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case ErrorParamsEmpty: + case ErrorParamEmpty: return "at least one given parameters is empty" - case ErrorParamsInvalid: + case ErrorParamInvalid: return "at least one given parameters is invalid" case ErrorValidatorError: return "config seems to be invalid" @@ -81,5 +79,5 @@ func getMessage(code liberr.CodeError) (message string) { return "the body match with not contains constraint" } - return liberr.NUL_MESSAGE + return liberr.NullMessage } diff --git a/request/model.go b/request/model.go index 55c40ab..1c2e4b7 100644 --- a/request/model.go +++ b/request/model.go @@ -646,7 +646,7 @@ func (r *request) Do() (*http.Response, liberr.Error) { defer r.s.Unlock() if r.m == "" || r.u == nil || r.u.String() == "" { - return nil, ErrorParamsInvalid.Error(nil) + return nil, ErrorParamInvalid.Error(nil) } var ( diff --git a/request/options.go b/request/options.go index 6301f6f..986cb0b 100644 --- a/request/options.go +++ b/request/options.go @@ -30,12 +30,13 @@ import ( "fmt" "net/http" + libsts "github.com/nabbar/golib/status/config" + libval "github.com/go-playground/validator/v10" libtls "github.com/nabbar/golib/certificates" libcfg "github.com/nabbar/golib/config" liberr "github.com/nabbar/golib/errors" libhtc "github.com/nabbar/golib/httpcli" - libsts "github.com/nabbar/golib/status" ) type OptionsCredentials struct { diff --git a/router/auth.go b/router/auth.go index dfa7050..84466cb 100644 --- a/router/auth.go +++ b/router/auth.go @@ -104,7 +104,7 @@ func (a authorization) Handler(c *gin.Context) { auth := c.Request.Header.Get(HEAD_AUTH_SEND) if auth == "" { - AuthRequire(c, HEADER_AUTH_MISSING.Error(nil).GetErrorFull("")) + AuthRequire(c, ErrorHeaderAuthMissing.Error(nil).GetErrorFull("")) return } @@ -118,7 +118,7 @@ func (a authorization) Handler(c *gin.Context) { } if authValue == "" { - AuthRequire(c, HEADER_AUTH_EMPTY.Error(nil).GetErrorFull("")) + AuthRequire(c, ErrorHeaderAuthEmpty.Error(nil).GetErrorFull("")) return } else { code, err := a.check(authValue) @@ -130,12 +130,12 @@ func (a authorization) Handler(c *gin.Context) { r(c) } case AUTH_CODE_REQUIRE: - AuthRequire(c, HEADER_AUTH_REQUIRE.Error(err).GetErrorFull("")) + AuthRequire(c, ErrorHeaderAuthRequire.Error(err).GetErrorFull("")) case AUTH_CODE_FORBIDDEN: - AuthForbidden(c, HEADER_AUTH_FORBIDDEN.Error(err).GetErrorFull("")) + AuthForbidden(c, ErrorHeaderAuthForbidden.Error(err).GetErrorFull("")) default: c.Errors = append(c.Errors, &gin.Error{ - Err: HEADER_AUTH_ERROR.Error(err).GetErrorFull(""), + Err: ErrorHeaderAuth.Error(err).GetErrorFull(""), Type: gin.ErrorTypePrivate, }) c.AbortWithStatus(http.StatusInternalServerError) diff --git a/router/error.go b/router/error.go index ad63f77..135087b 100644 --- a/router/error.go +++ b/router/error.go @@ -26,51 +26,43 @@ package router -import errors "github.com/nabbar/golib/errors" +import ( + "fmt" -const ( - EMPTY_PARAMS errors.CodeError = iota + errors.MinPkgRouter - HEADER_AUTH_MISSING - HEADER_AUTH_EMPTY - HEADER_AUTH_REQUIRE - HEADER_AUTH_FORBIDDEN - HEADER_AUTH_ERROR + liberr "github.com/nabbar/golib/errors" ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} +const ( + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgRouter + ErrorHeaderAuth + ErrorHeaderAuthMissing + ErrorHeaderAuthEmpty + ErrorHeaderAuthRequire + ErrorHeaderAuthForbidden +) func init() { - isCodeError = errors.ExistInMapMessage(EMPTY_PARAMS) - errors.RegisterIdFctMessage(EMPTY_PARAMS, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/router")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case EMPTY_PARAMS: + case ErrorParamEmpty: return "given parameters is empty" - - case HEADER_AUTH_MISSING: + case ErrorHeaderAuthMissing: return "missing authorization header" - - case HEADER_AUTH_EMPTY: + case ErrorHeaderAuthEmpty: return "authorization header is empty" - - case HEADER_AUTH_REQUIRE: + case ErrorHeaderAuthRequire: return "authorization check failed, authorization still require" - - case HEADER_AUTH_FORBIDDEN: + case ErrorHeaderAuthForbidden: return "authorization check success but unauthorized client" - - case HEADER_AUTH_ERROR: + case ErrorHeaderAuth: return "authorization check return an invalid response code" - - case errors.UNK_ERROR: - return "" } - return "" + return liberr.NullMessage } diff --git a/semaphore/error.go b/semaphore/error.go index dc11fbc..d52e340 100644 --- a/semaphore/error.go +++ b/semaphore/error.go @@ -26,30 +26,28 @@ package semaphore -import errors "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgSemaphore + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgSemaphore ErrorWorkerNew ErrorWorkerWaitAll ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/semaphore")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorWorkerNew: return "error on acquire one new semaphore worker" @@ -57,5 +55,5 @@ func getMessage(code errors.CodeError) (message string) { return "error on acquire to wait all pending thread" } - return "" + return liberr.NullMessage } diff --git a/smtp/config.go b/smtp/config.go index fe4cebb..884232c 100644 --- a/smtp/config.go +++ b/smtp/config.go @@ -29,10 +29,11 @@ import ( "fmt" "net/url" + libsts "github.com/nabbar/golib/status/config" + libval "github.com/go-playground/validator/v10" libtls "github.com/nabbar/golib/certificates" liberr "github.com/nabbar/golib/errors" - libsts "github.com/nabbar/golib/status" ) type ConfigModel struct { diff --git a/smtp/dial.go b/smtp/dial.go index d7ea423..1c7297b 100644 --- a/smtp/dial.go +++ b/smtp/dial.go @@ -85,10 +85,10 @@ func (s *smtpClient) client(ctx context.Context, addr string, tlsConfig *tls.Con }() if s.cfg.GetTlsMode() == TLS_STARTTLS && tlsConfig == nil { - err = ErrorParamsEmpty.Error(nil) + err = ErrorParamEmpty.Error(nil) return } else if s.cfg.GetTlsMode() == TLS_TLS && tlsConfig == nil { - err = ErrorParamsEmpty.Error(nil) + err = ErrorParamEmpty.Error(nil) return } diff --git a/smtp/error.go b/smtp/error.go index 9b8c424..fe3d39e 100644 --- a/smtp/error.go +++ b/smtp/error.go @@ -26,10 +26,14 @@ package smtp -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgSMTP + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgSMTP ErrorConfigValidator ErrorConfigInvalidDSN ErrorConfigInvalidNetwork @@ -47,22 +51,16 @@ const ( ErrorSMTPLineCRLF ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/smtp")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorConfigValidator: return "invalid config, validation error" @@ -96,5 +94,5 @@ func getMessage(code errors.CodeError) (message string) { return "smtp: A line must not contain CR or LF" } - return "" + return liberr.NullMessage } diff --git a/smtp/interface.go b/smtp/interface.go index e8fafdf..5d33830 100644 --- a/smtp/interface.go +++ b/smtp/interface.go @@ -36,6 +36,8 @@ import ( "strings" "sync" + "github.com/nabbar/golib/status/config" + libtls "github.com/nabbar/golib/certificates" liberr "github.com/nabbar/golib/errors" @@ -70,8 +72,8 @@ type Config interface { SetTLSServerName(serverName string) GetTlSServerName() string - SetStatusConfig(sts libsts.ConfigStatus) - GetStatusConfig() libsts.ConfigStatus + SetStatusConfig(sts config.ConfigStatus) + GetStatusConfig() config.ConfigStatus GetDsn() string } @@ -102,7 +104,7 @@ func NewSMTP(cfg Config, tlsConfig *tls.Config) (SMTP, liberr.Error) { } if cfg == nil { - return nil, ErrorParamsEmpty.Error(nil) + return nil, ErrorParamEmpty.Error(nil) } else { return &smtpClient{ mut: sync.Mutex{}, diff --git a/static/error.go b/static/error.go index d127f66..918a3d1 100644 --- a/static/error.go +++ b/static/error.go @@ -26,32 +26,30 @@ package static -import "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgStatic + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgStatic ErrorFileInfo ErrorFileOpen ErrorFiletemp ErrorFileNotFound ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/static")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorFileInfo: return "cannot get file info" @@ -63,5 +61,5 @@ func getMessage(code errors.CodeError) (message string) { return "file not found" } - return "" + return liberr.NullMessage } diff --git a/static/model.go b/static/model.go index 7b912bf..aaed99d 100644 --- a/static/model.go +++ b/static/model.go @@ -43,6 +43,8 @@ import ( "sync/atomic" "time" + "golang.org/x/exp/slices" + "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/render" @@ -77,16 +79,6 @@ func (s *staticHandler) _makeRoute(group, route string) string { return path.Join(group, route) } -func (s *staticHandler) _IsInSlice(sl []string, val string) bool { - for _, v := range sl { - if v == val { - return true - } - } - - return false -} - func (s *staticHandler) _getSize() int64 { s.m.Lock() defer s.m.Unlock() @@ -297,7 +289,7 @@ func (s *staticHandler) _setRouter(val []string) { func (s *staticHandler) _listEmbed(root string) ([]fs.DirEntry, liberr.Error) { if root == "" { - return nil, ErrorParamsEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) + return nil, ErrorParamEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) } s.m.Lock() @@ -316,7 +308,7 @@ func (s *staticHandler) _listEmbed(root string) ([]fs.DirEntry, liberr.Error) { func (s *staticHandler) _fileGet(pathFile string) (fs.FileInfo, io.ReadCloser, liberr.Error) { if pathFile == "" { - return nil, nil, ErrorParamsEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) + return nil, nil, ErrorParamEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) } if inf, err := s._fileInfo(pathFile); err != nil { @@ -332,7 +324,7 @@ func (s *staticHandler) _fileGet(pathFile string) (fs.FileInfo, io.ReadCloser, l func (s *staticHandler) _fileInfo(pathFile string) (fs.FileInfo, liberr.Error) { if pathFile == "" { - return nil, ErrorParamsEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) + return nil, ErrorParamEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) } s.m.Lock() @@ -364,7 +356,7 @@ func (s *staticHandler) _fileInfo(pathFile string) (fs.FileInfo, liberr.Error) { func (s *staticHandler) _fileBuff(pathFile string) (io.ReadCloser, liberr.Error) { if pathFile == "" { - return nil, ErrorParamsEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) + return nil, ErrorParamEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) } s.m.Lock() @@ -383,7 +375,7 @@ func (s *staticHandler) _fileBuff(pathFile string) (io.ReadCloser, liberr.Error) func (s *staticHandler) _fileTemp(pathFile string) (libiot.FileProgress, liberr.Error) { if pathFile == "" { - return nil, ErrorParamsEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) + return nil, ErrorParamEmpty.ErrorParent(fmt.Errorf("pathfile is empty")) } s.m.Lock() @@ -462,7 +454,7 @@ func (s *staticHandler) GetIndex(group, route string) string { continue } - if s._IsInSlice(r, route) { + if slices.Contains(r, route) { return f } } @@ -533,7 +525,7 @@ func (s *staticHandler) IsIndexForRoute(pathFile, group, route string) bool { return false } - return s._IsInSlice(val, s._makeRoute(group, route)) + return slices.Contains(val, s._makeRoute(group, route)) } func (s *staticHandler) IsRedirect(group, route string) bool { diff --git a/status/config.go b/status/config/config.go similarity index 83% rename from status/config.go rename to status/config/config.go index 85b45e5..ac26079 100644 --- a/status/config.go +++ b/status/config/config.go @@ -24,15 +24,17 @@ * */ -package status +package config import ( "bytes" "encoding/json" "time" - libcfg "github.com/nabbar/golib/config" + "github.com/nabbar/golib/status" + libcfg "github.com/nabbar/golib/config" + libsts "github.com/nabbar/golib/status" spfcbr "github.com/spf13/cobra" spfvpr "github.com/spf13/viper" ) @@ -76,8 +78,8 @@ func DefaultConfig(indent string) []byte { func RegisterFlag(prefix string, Command *spfcbr.Command, Viper *spfvpr.Viper) error { _ = Command.PersistentFlags().Bool(prefix+".mandatory", true, "define if the component must be available for the api. If yes, api status will be KO if this component is down. If no, api status can be OK if this component is down.") - _ = Command.PersistentFlags().String(prefix+".message_ok", DefMessageOK, "define the message if the status is OK.") - _ = Command.PersistentFlags().String(prefix+".message_ko", DefMessageKO, "define the message if the status is KO.") + _ = Command.PersistentFlags().String(prefix+".message_ok", status.DefMessageOK, "define the message if the status is OK.") + _ = Command.PersistentFlags().String(prefix+".message_ko", status.DefMessageKO, "define the message if the status is KO.") _ = Command.PersistentFlags().Duration(prefix+".cache_timeout_info", time.Hour, "define the time between checking the component information (name, release, ...), to prevent asking it too many.") _ = Command.PersistentFlags().Duration(prefix+".cache_timeout_health", 5*time.Second, "define the time between checking the component health to prevent asking it too many.") @@ -98,20 +100,20 @@ func RegisterFlag(prefix string, Command *spfcbr.Command, Viper *spfvpr.Viper) e func (c *ConfigStatus) fctMessage() (msgOk string, msgKO string) { if c.MessageOK == "" { - c.MessageOK = DefMessageOK + c.MessageOK = status.DefMessageOK } if c.MessageKO == "" { - c.MessageKO = DefMessageKO + c.MessageKO = status.DefMessageKO } return c.MessageOK, c.MessageKO } -func (c *ConfigStatus) RegisterStatus(sts RouteStatus, key string, fctInfo FctInfo, fctHealth FctHealth) { - sts.ComponentNew(key, NewComponent(c.Mandatory, fctInfo, fctHealth, c.fctMessage, c.CacheTimeoutInfo, c.CacheTimeoutHealth)) +func (c *ConfigStatus) RegisterStatus(sts libsts.RouteStatus, key string, fctInfo libsts.FctInfo, fctHealth libsts.FctHealth) { + sts.ComponentNew(key, status.NewComponent(c.Mandatory, fctInfo, fctHealth, c.fctMessage, c.CacheTimeoutInfo, c.CacheTimeoutHealth)) } -func (c *ConfigStatus) Component(fctInfo FctInfo, fctHealth FctHealth) Component { - return NewComponent(c.Mandatory, fctInfo, fctHealth, c.fctMessage, c.CacheTimeoutInfo, c.CacheTimeoutHealth) +func (c *ConfigStatus) Component(fctInfo libsts.FctInfo, fctHealth libsts.FctHealth) libsts.Component { + return status.NewComponent(c.Mandatory, fctInfo, fctHealth, c.fctMessage, c.CacheTimeoutInfo, c.CacheTimeoutHealth) } diff --git a/status/health.go b/status/health.go index 2c84eda..7ae4bc7 100644 --- a/status/health.go +++ b/status/health.go @@ -93,7 +93,7 @@ func (s *status) Get(x *gin.Context) StatusResponse { if err != nil { c.Status = DefMessageKO c.Message = msgKO - liblog.ErrorLevel.LogGinErrorCtx(liblog.DebugLevel, "get health status", err, x) + liblog.ErrorLevel.LogErrorCtx(liblog.DebugLevel, "get health status", err) } else { c.Status = DefMessageOK c.Message = msgOk diff --git a/status/interface.go b/status/interface.go index e39ea6c..75ea0c9 100644 --- a/status/interface.go +++ b/status/interface.go @@ -27,64 +27,14 @@ package status import ( "net/http" - "sync" "sync/atomic" - "github.com/gin-gonic/gin" librtr "github.com/nabbar/golib/router" + + "github.com/gin-gonic/gin" libver "github.com/nabbar/golib/version" ) -const DefMessageOK = "OK" -const DefMessageKO = "KO" - -type Response struct { - InfoResponse - StatusResponse - - m sync.Mutex - Components []CptResponse `json:"components"` -} - -func (r Response) IsOk() bool { - if len(r.Components) < 1 { - return true - } - - for _, c := range r.Components { - if c.Status != DefMessageOK { - return false - } - } - - return true -} - -func (r Response) IsOkMandatory() bool { - if len(r.Components) < 1 { - return true - } - - for _, c := range r.Components { - if !c.Mandatory { - continue - } - - if c.Status != DefMessageOK { - return false - } - } - - return true -} - -func (r *Response) appendNewCpt(cpt CptResponse) { - r.m.Lock() - defer r.m.Unlock() - - r.Components = append(r.Components, cpt) -} - type RouteStatus interface { MiddlewareAdd(mdw ...gin.HandlerFunc) HttpStatusCode(codeOk, codeKO, codeWarning int) diff --git a/config/tools.go b/status/response.go similarity index 61% rename from config/tools.go rename to status/response.go index 60f6a6d..c38b401 100644 --- a/config/tools.go +++ b/status/response.go @@ -21,21 +21,58 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * - * */ -package config +package status -func stringIsInSlice(list []string, key string) bool { - if len(list) < 1 { - return false +import "sync" + +const DefMessageOK = "OK" +const DefMessageKO = "KO" + +type Response struct { + InfoResponse + StatusResponse + + m sync.Mutex + Components []CptResponse `json:"components"` +} + +func (r Response) IsOk() bool { + if len(r.Components) < 1 { + return true } - for _, k := range list { - if k == key { - return true + for _, c := range r.Components { + if c.Status != DefMessageOK { + return false } } - return false + return true +} + +func (r Response) IsOkMandatory() bool { + if len(r.Components) < 1 { + return true + } + + for _, c := range r.Components { + if !c.Mandatory { + continue + } + + if c.Status != DefMessageOK { + return false + } + } + + return true +} + +func (r *Response) appendNewCpt(cpt CptResponse) { + r.m.Lock() + defer r.m.Unlock() + + r.Components = append(r.Components, cpt) } diff --git a/version/error.go b/version/error.go index 6fed0ab..fbfe47f 100644 --- a/version/error.go +++ b/version/error.go @@ -26,31 +26,29 @@ package version -import errors "github.com/nabbar/golib/errors" +import ( + "fmt" + + liberr "github.com/nabbar/golib/errors" +) const ( - ErrorParamsEmpty errors.CodeError = iota + errors.MinPkgVersion + ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgVersion ErrorGoVersionInit ErrorGoVersionRuntime ErrorGoVersionConstraint ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = errors.ExistInMapMessage(ErrorParamsEmpty) - errors.RegisterIdFctMessage(ErrorParamsEmpty, getMessage) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/version")) + } + liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } -func getMessage(code errors.CodeError) (message string) { +func getMessage(code liberr.CodeError) (message string) { switch code { - case errors.UNK_ERROR: - return "" - case ErrorParamsEmpty: + case ErrorParamEmpty: return "given parameters is empty" case ErrorGoVersionInit: return "init GoVersion contraint error" @@ -60,5 +58,5 @@ func getMessage(code errors.CodeError) (message string) { return "current binary is build with a non-compatible version of Go" } - return "" + return liberr.NullMessage } diff --git a/viper/errors.go b/viper/errors.go index 8d785da..b801dfb 100644 --- a/viper/errors.go +++ b/viper/errors.go @@ -27,6 +27,8 @@ package viper import ( + "fmt" + liberr "github.com/nabbar/golib/errors" ) @@ -44,21 +46,15 @@ const ( ErrorConfigIsDefault ) -var isCodeError = false - -func IsCodeError() bool { - return isCodeError -} - func init() { - isCodeError = liberr.ExistInMapMessage(ErrorParamEmpty) + if liberr.ExistInMapMessage(ErrorParamEmpty) { + panic(fmt.Errorf("error code collision with package golib/viper")) + } liberr.RegisterIdFctMessage(ErrorParamEmpty, getMessage) } func getMessage(code liberr.CodeError) (message string) { switch code { - case liberr.UNK_ERROR: - return "" case ErrorParamMissing: return "at least one parameter is missing" case ErrorHomePathNotFound: @@ -81,5 +77,5 @@ func getMessage(code liberr.CodeError) (message string) { return "cannot read config, use default config" } - return "" + return liberr.NullMessage }