package main import ( "bytes" "flag" "fmt" "go/weather/internal" "go/weather/internal/poller" "go/weather/internal/storage" "go/weather/internal/web" "go/weather/pkg/logger" "io" "io/ioutil" "os" "os/signal" "time" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/gohcl" "github.com/hashicorp/hcl/v2/hclsyntax" "go.uber.org/zap" ) const bucket = "weather" func main() { var interval time.Duration var filename string flag.DurationVar(&interval, "check-interval", time.Second*30, "the sleep duration between multiple call to remote weather api") flag.StringVar(&filename, "filename", "config.hcl", "configuration filename") flag.Parse() loggerLevel := zap.NewAtomicLevelAt(zap.DebugLevel) defaultLogger := logger.NewLogger("poller", "weather.log", loggerLevel) defaultLoggerSugar := defaultLogger.Sugar() defer defaultLogger.Sync() if filename == "config.hcl" { dir, err := os.Getwd() if err != nil { defaultLoggerSugar.Fatal("Fail to determine current directory to load default ./config.hcl file") } filename = fmt.Sprintf("%s%c%s", dir, os.PathSeparator, filename) } src, err := ioutil.ReadFile(filename) if err != nil { defaultLoggerSugar.Fatal("Missing required parameter : filename") } file, diags := hclsyntax.ParseConfig(src, filename, hcl.Pos{Line: 1, Column: 1}) if diags.HasErrors() { defaultLoggerSugar.Fatal("config parse", zap.Error(diags)) } config := &internal.WeatherConfig{} diags = gohcl.DecodeBody(file.Body, nil, config) if diags.HasErrors() { defaultLoggerSugar.Fatal("config parse", zap.Error(diags)) } if config.OpenweatherSecret == "" { defaultLoggerSugar.Fatal("Missing required parameter : openweather-secret") } addr := web.NewListenAddr("api.openweathermap.org", 443) poller := poller.NewWeatherPoller(defaultLogger, addr, 45.75, 4.85, config.OpenweatherSecret) // s3storage := storage.NewS3Storage(defaultLogger, bucket) fileStorage := storage.NewFileStorage(defaultLogger, "db.json") go func() { for { data := poller.Poll() defer data.Close() var buf bytes.Buffer b, err := ioutil.ReadAll(io.TeeReader(data, &buf)) if err != nil { defaultLogger.Sugar().Fatal("Wait next poll") } fileStorage.Store(bytes.NewReader(b)) // s3storage.Store(&buf) defaultLogger.Sugar().Debug("Wait next poll") time.Sleep(interval) } }() c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) <-c defaultLogger.Sugar().Info("shutting down") os.Exit(0) }