65 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			65 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package config
 | |
| 
 | |
| import (
 | |
| 	"fmt"
 | |
| 	"log"
 | |
| 	"log/slog"
 | |
| 	"path/filepath"
 | |
| 	"slices"
 | |
| 
 | |
| 	"github.com/spf13/viper"
 | |
| 
 | |
| 	"git.kplus.net.ua/yevhen/resource-scraper/types/constant"
 | |
| )
 | |
| 
 | |
| func New() {
 | |
| 	configFilePath := viper.GetString(constant.FlagConfigFile)
 | |
| 	configName := filepath.Base(configFilePath)
 | |
| 
 | |
| 	dir := filepath.Dir(configFilePath)
 | |
| 	if dir == configName && dir == "." {
 | |
| 		configName = "default"
 | |
| 	}
 | |
| 
 | |
| 	configDir, _ := filepath.Abs(dir)
 | |
| 
 | |
| 	viper.AddConfigPath(configDir)
 | |
| 	viper.SetConfigName(configName)
 | |
| 	err := viper.ReadInConfig()
 | |
| 	if err != nil { // Handle errors reading the config file
 | |
| 		panic(fmt.Errorf("fatal error config file: %w", err))
 | |
| 	}
 | |
| 
 | |
| 	viper.SetConfigName("secret")
 | |
| 	err = viper.MergeInConfig()
 | |
| 	if err != nil { // Handle errors reading the config file
 | |
| 		panic(fmt.Errorf("fatal error secret file: %w", err))
 | |
| 	}
 | |
| 
 | |
| 	slog.Info("using config", "path", filepath.Join(configDir, configName))
 | |
| 	viper.SetDefault(constant.CfgKeyConfigDir, configDir)
 | |
| 
 | |
| 	// Scopes validating
 | |
| 	scope := viper.GetString(constant.CfgKeyScopeEnable)
 | |
| 	scopesAllowed := viper.GetStringSlice("scope.allow")
 | |
| 
 | |
| 	if !slices.Contains(scopesAllowed, scope) {
 | |
| 		scope = viper.GetString("scope.default")
 | |
| 
 | |
| 		if scope == "" {
 | |
| 			scope = constant.ScopeInfo
 | |
| 		}
 | |
| 	}
 | |
| 
 | |
| 	fmt.Println("scope", scope)
 | |
| 
 | |
| 	viper.SetConfigName(scope)
 | |
| 	viper.AddConfigPath(filepath.Join(configDir, "scope"))
 | |
| 	err = viper.MergeInConfig()
 | |
| 	if err == nil {
 | |
| 		viper.SetDefault(constant.CfgKeyScopeEnable, scope)
 | |
| 	} else {
 | |
| 		log.Fatalf("fatal error config file: %v", err)
 | |
| 	}
 | |
| }
 |