From 87b18c7f7e73d716265874e5cba4815c6b732e5d Mon Sep 17 00:00:00 2001 From: Bilal Date: Fri, 8 May 2020 07:50:27 +0200 Subject: [PATCH] Handle config as struct with values from ENV file --- config/config.go | 59 ++++++++++++++++++++++++++++++++++++++++ structures/structures.go | 8 ++++++ 2 files changed, 67 insertions(+) create mode 100644 config/config.go diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..cb6ac98 --- /dev/null +++ b/config/config.go @@ -0,0 +1,59 @@ +package config + +import ( + "github.com/joho/godotenv" + "gitlab.com/saburly/kiviscraplib/structures" + "log" + "os" + "strconv" +) + +var ClientConfig structures.ClientConfig +var defaultValues = make(map[string]string) + +func InitConfig() { + err := godotenv.Load() + if err != nil { + log.Fatal("Unable to load ENV variables") + } + + initDefaultValues() + generateClientConfigObject() +} + +func generateClientConfigObject() { + ClientConfig.ConnectionsCount = getInt("CLIENT_CONNECTIONS_COUNT") + ClientConfig.ConnectionTimeout = getInt("CLIENT_CONNECTION_TIMEOUT") + ClientConfig.WorkerServerAddress = getString("WORKER_SERVER_ADDRESS") + ClientConfig.RequestMessagePrefix = getString("REQUEST_MESSAGE_PREFIX") + ClientConfig.ProxyListBaseURL = getString("PROXY_LIST_BASE_URL") +} + +func initDefaultValues() { + defaultValues["CLIENT_CONNECTIONS_COUNT"] = "5" + defaultValues["CLIENT_CONNECTION_TIMEOUT"] = "2" + defaultValues["WORKER_SERVER_ADDRESS"] = "127.0.0.1:1338" + defaultValues["REQUEST_MESSAGE_PREFIX"] = "URL " + defaultValues["PROXY_LIST_BASE_URL"] = "https://www.proxy-list.download/api/v1/get?type=" +} + +func getInt(key string) int { + value := os.Getenv(key) + if len(value) == 0 { + value = defaultValues[key] + } + + numericalValue, err := strconv.Atoi(value) + if err != nil { + log.Fatalf("Cannot convert ENV value for %s to the integer", key) + } + return numericalValue +} + +func getString(key string) string { + value := os.Getenv(key) + if len(value) == 0 { + return defaultValues[key] + } + return value +} diff --git a/structures/structures.go b/structures/structures.go index ce705e5..d254e1e 100644 --- a/structures/structures.go +++ b/structures/structures.go @@ -20,3 +20,11 @@ type ProxyServer struct { Type string Address string } + +type ClientConfig struct { + ConnectionsCount int + ConnectionTimeout int // In seconds + WorkerServerAddress string + RequestMessagePrefix string + ProxyListBaseURL string +}