github.com/ars0915/glossika-exercise@v0.0.0-20240904180321-a5617a00d892/config/config.go (about)

     1  package config
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  	"sync"
     9  	"time"
    10  
    11  	"github.com/spf13/viper"
    12  )
    13  
    14  var defaultConf = []byte(`
    15  # example: debug, release, test
    16  CORE_MODE=debug
    17  CORE_PORT=8080
    18  `)
    19  
    20  var Conf ConfENV
    21  var once sync.Once
    22  
    23  type ConfENV struct {
    24  	Core  SectionCore
    25  	Log   SectionLog
    26  	DB    SectionDB
    27  	Redis SectionRedis
    28  	JWT   SectionJWT
    29  }
    30  
    31  type SectionCore struct {
    32  	Mode string
    33  	Port string
    34  }
    35  
    36  type SectionLog struct {
    37  	Format string
    38  	Output string
    39  	Level  string
    40  }
    41  
    42  type SectionDB struct {
    43  	Host               string
    44  	Port               string
    45  	Database           string
    46  	Username           string
    47  	Password           string
    48  	MaxIdleConns       int
    49  	MaxOpenConns       int
    50  	MaxConnectionRetry int
    51  	RetryDelay         time.Duration
    52  }
    53  
    54  type SectionJWT struct {
    55  	Secret         string
    56  	ExpireDuration time.Duration
    57  }
    58  
    59  type SectionRedis struct {
    60  	Hosts string
    61  }
    62  
    63  func InitConf(confPath string) error {
    64  	var err error
    65  	once.Do(func() {
    66  		Conf, err = LoadConf(confPath)
    67  	})
    68  	return err
    69  }
    70  
    71  // LoadConf load config from file and read in environment variables that match
    72  func LoadConf(confPath string) (ConfENV, error) {
    73  	var conf ConfENV
    74  
    75  	viper.SetConfigType("env")
    76  	viper.AutomaticEnv() // read in environment variables that match
    77  	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
    78  
    79  	if confPath != "" {
    80  		content, err := os.ReadFile(confPath)
    81  
    82  		if err != nil {
    83  			return conf, err
    84  		}
    85  
    86  		if err := viper.ReadConfig(bytes.NewBuffer(content)); err != nil {
    87  			return conf, err
    88  		}
    89  	} else {
    90  		// Search config in home directory with name ".gorush" (without extension).
    91  		viper.AddConfigPath(".")
    92  		// viper.SetConfigName("")
    93  		viper.SetConfigFile(".env")
    94  
    95  		// If a config file is found, read it in.
    96  		if err := viper.ReadInConfig(); err == nil {
    97  			fmt.Println("Using config file:", viper.ConfigFileUsed())
    98  		} else {
    99  			// load default config
   100  			if err := viper.ReadConfig(bytes.NewBuffer(defaultConf)); err != nil {
   101  				return conf, err
   102  			}
   103  		}
   104  	}
   105  
   106  	conf.Core.Mode = viper.GetString("core_mode")
   107  	conf.Core.Port = viper.GetString("core_port")
   108  	if len(conf.Core.Port) == 0 {
   109  		conf.Core.Port = "8080"
   110  	}
   111  
   112  	conf.Log.Format = viper.GetString("log_format")
   113  	conf.Log.Level = viper.GetString("log_level")
   114  	conf.Log.Output = viper.GetString("log_output")
   115  
   116  	conf.DB.Host = viper.GetString("db_host")
   117  	conf.DB.Port = viper.GetString("db_port")
   118  	conf.DB.Username = viper.GetString("db_username")
   119  	conf.DB.Password = viper.GetString("db_password")
   120  	conf.DB.Database = viper.GetString("db_database")
   121  	conf.DB.MaxIdleConns = viper.GetInt("db_max_idle_conns")
   122  	conf.DB.MaxOpenConns = viper.GetInt("db_max_open_conns")
   123  	conf.DB.MaxConnectionRetry = viper.GetInt("db_max_connection_retry")
   124  	conf.DB.RetryDelay = viper.GetDuration("db_retry_delay")
   125  
   126  	conf.Redis.Hosts = viper.GetString("redis_hosts")
   127  
   128  	conf.JWT.Secret = viper.GetString("jwt_secret")
   129  	conf.JWT.ExpireDuration = viper.GetDuration("jwt_expire_duration")
   130  
   131  	return conf, nil
   132  }