Handle config as struct with values from ENV file
This commit is contained in:
59
config/config.go
Normal file
59
config/config.go
Normal file
@@ -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
|
||||||
|
}
|
||||||
@@ -20,3 +20,11 @@ type ProxyServer struct {
|
|||||||
Type string
|
Type string
|
||||||
Address string
|
Address string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ClientConfig struct {
|
||||||
|
ConnectionsCount int
|
||||||
|
ConnectionTimeout int // In seconds
|
||||||
|
WorkerServerAddress string
|
||||||
|
RequestMessagePrefix string
|
||||||
|
ProxyListBaseURL string
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user