Alexey Kim 1 жил өмнө
parent
commit
cd4bfcc1ec

+ 12 - 48
config/config.go

@@ -2,62 +2,26 @@ package config
 
 import (
 	"fmt"
-	"gopkg.in/yaml.v3"
-	"os"
-	"reflect"
+	"time"
 )
 
-type IConfig interface {
-	Invalidate() error
+type Configuration struct {
+	Timeout   int    `yaml:"timeout"`
+	SecretKey string `yaml:"secret-key"`
 }
 
-func Invalidate(config IConfig) error {
-	if config == nil {
-		return fmt.Errorf("config must not be a nil")
+func (c Configuration) Invalidate() error {
+	if c.Timeout < 1 {
+		c.Timeout = 30
 	}
 
-	val := reflect.ValueOf(config)
-	if val.Kind() != reflect.Struct {
-		if val.IsZero() {
-			return fmt.Errorf("config is empty")
-		}
-
-		val = reflect.ValueOf(config).Elem()
-	}
-
-	for i := 0; i < val.NumField(); i++ {
-		if !val.Field(i).CanInterface() || val.Field(i).IsZero() {
-			continue
-		}
-
-		if elm, ok := val.Field(i).Interface().(IConfig); ok {
-			if er := elm.Invalidate(); er != nil {
-				return er
-			}
-		}
+	if c.SecretKey == "" {
+		return fmt.Errorf("`secret-key` must not be an empty string")
 	}
 
-	return nil
+	return Invalidate(c)
 }
 
-func ReadConfig[T IConfig](path string) (*T, error) {
-	var (
-		cfg = new(T)
-		fd  []byte
-		err error
-	)
-
-	if fd, err = os.ReadFile(path); err != nil {
-		return nil, err
-	}
-
-	if err = yaml.Unmarshal(fd, cfg); err != nil {
-		return nil, err
-	}
-
-	if err = Invalidate(*cfg); err != nil {
-		return nil, err
-	}
-
-	return cfg, nil
+func (c Configuration) TimeoutDuration() time.Duration {
+	return time.Duration(c.Timeout) * time.Second
 }

+ 63 - 0
config/iconfig.go

@@ -0,0 +1,63 @@
+package config
+
+import (
+	"fmt"
+	"gopkg.in/yaml.v3"
+	"os"
+	"reflect"
+)
+
+type IConfig interface {
+	Invalidate() error
+}
+
+func Invalidate(config IConfig) error {
+	if config == nil {
+		return fmt.Errorf("config must not be a nil")
+	}
+
+	val := reflect.ValueOf(config)
+	if val.Kind() != reflect.Struct {
+		if val.IsZero() {
+			return fmt.Errorf("config is empty")
+		}
+
+		val = reflect.ValueOf(config).Elem()
+	}
+
+	for i := 0; i < val.NumField(); i++ {
+		if !val.Field(i).CanInterface() || val.Field(i).IsZero() {
+			continue
+		}
+
+		if elm, ok := val.Field(i).Interface().(IConfig); ok {
+			if er := elm.Invalidate(); er != nil {
+				return er
+			}
+		}
+	}
+
+	return nil
+}
+
+func ReadConfig[T IConfig](path string) (*T, error) {
+	var (
+		cfg = new(T)
+		fd  []byte
+		err error
+	)
+
+	if fd, err = os.ReadFile(path); err != nil {
+		return nil, err
+	}
+
+	if err = yaml.Unmarshal(fd, cfg); err != nil {
+		return nil, err
+	}
+
+	if err = Invalidate(*cfg); err != nil {
+		return nil, err
+	}
+
+	return cfg, nil
+}

+ 0 - 0
config/config_test.go → config/iconfig_test.go