package internal import ( "fmt" "go/weather/internal/storage" "io/ioutil" "os" "path/filepath" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/gohcl" "github.com/hashicorp/hcl/v2/hclsyntax" "go.uber.org/zap" ) //WeatherConfig weather application relative configuration file // this configuration is common to weather server and poller type WeatherConfig struct { OpenweatherSecret string `hcl:"openweather_secret"` S3Storage *storage.WeatherS3StorageConfig `hcl:"s3,block"` } //ParseConfiguration parse configuration from filename path func ParseConfiguration(sLogger *zap.SugaredLogger, filename string) *WeatherConfig { dir, err := os.Getwd() if err != nil { sLogger.Fatalw("Fail to determine current directory to load default ./config.hcl file", zap.Error(err)) } sLogger.Debugf("current dir is %s", dir) if filename == "config.hcl" { filename = fmt.Sprintf("%s%c%s", dir, os.PathSeparator, filename) } relativeFilename, err := filepath.Rel(dir, filename) if err != nil { sLogger.Fatalw(fmt.Sprintf("Fail to determine configuration relative directory for file %s", filename), zap.Error(err)) } src, err := ioutil.ReadFile(relativeFilename) if err != nil { sLogger.Fatalw(fmt.Sprintf("Missing required parameter filename got : %s", relativeFilename), zap.Error(err)) } file, diags := hclsyntax.ParseConfig(src, relativeFilename, hcl.Pos{Line: 1, Column: 1}) if diags.HasErrors() { sLogger.Fatal("config parse", zap.Error(diags)) } config := &WeatherConfig{} diags = gohcl.DecodeBody(file.Body, nil, config) if diags.HasErrors() { sLogger.Fatal("config decode", zap.Error(diags)) } if config.OpenweatherSecret == "" { sLogger.Fatal("Missing required parameter : openweather-secret") } return config }