From c7a8372516e76be5c8493248c2347b9577d5bda4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ferdinand=20M=C3=BCtsch?= Date: Thu, 16 May 2019 22:51:11 +0200 Subject: [PATCH] Introduce config ini. --- config.ini | 5 +++++ main.go | 30 +++++++++++++++++++----------- models/config.go | 15 +++++++++------ 3 files changed, 33 insertions(+), 17 deletions(-) create mode 100644 config.ini diff --git a/config.ini b/config.ini new file mode 100644 index 0000000..056e07a --- /dev/null +++ b/config.ini @@ -0,0 +1,5 @@ +[server] +port = 3000 + +[data] +aggregation_interval = 24h \ No newline at end of file diff --git a/main.go b/main.go index 60a5447..defc0ec 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "log" "net/http" "os" @@ -11,6 +12,7 @@ import ( "github.com/gorilla/mux" "github.com/jinzhu/gorm" "github.com/joho/godotenv" + ini "gopkg.in/ini.v1" "github.com/n1try/wakapi/middlewares" "github.com/n1try/wakapi/models" @@ -26,26 +28,32 @@ func readConfig() models.Config { log.Fatal(err) } - port, err := strconv.Atoi(os.Getenv("WAKAPI_PORT")) dbUser, valid := os.LookupEnv("WAKAPI_DB_USER") dbPassword, valid := os.LookupEnv("WAKAPI_DB_PASSWORD") dbHost, valid := os.LookupEnv("WAKAPI_DB_HOST") dbName, valid := os.LookupEnv("WAKAPI_DB_NAME") - if err != nil { - log.Fatal(err) - } if !valid { - log.Fatal("Config parameters missing.") + log.Fatal("Environment variables missing.") } + cfg, err := ini.Load("config.ini") + if err != nil { + log.Fatal(fmt.Sprintf("Fail to read file: %v", err)) + } + + port := cfg.Section("server").Key("port").MustInt() + intervalStr := cfg.Section("data").Key("aggregation_interval").String() + interval, _ := time.ParseDuration(intervalStr) + return models.Config{ - Port: port, - DbHost: dbHost, - DbUser: dbUser, - DbPassword: dbPassword, - DbName: dbName, - DbDialect: "mysql", + Port: port, + DbHost: dbHost, + DbUser: dbUser, + DbPassword: dbPassword, + DbName: dbName, + DbDialect: "mysql", + AggregationInterval: interval, } } diff --git a/models/config.go b/models/config.go index 436814a..80fe253 100644 --- a/models/config.go +++ b/models/config.go @@ -1,10 +1,13 @@ package models +import "time" + type Config struct { - Port int - DbHost string - DbUser string - DbPassword string - DbName string - DbDialect string + Port int + DbHost string + DbUser string + DbPassword string + DbName string + DbDialect string + AggregationInterval time.Duration }