From 31fc0856b86162634066cd730542a2a51ce7e6f2 Mon Sep 17 00:00:00 2001 From: max Date: Thu, 20 Oct 2022 11:57:41 -0500 Subject: [PATCH] Dependency injection, example .env, and config handling --- app/app.go | 12 ++++++++++++ config/config.go | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ env_example.json | 16 ++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 app/app.go create mode 100644 config/config.go create mode 100644 env_example.json diff --git a/app/app.go b/app/app.go new file mode 100644 index 0000000..f9d0d3c --- /dev/null +++ b/app/app.go @@ -0,0 +1,12 @@ +package app + +import ( + "GoWeb/config" + "database/sql" +) + +// App contains and supplies available configurations and connections +type App struct { + Config config.Configuration + Db *sql.DB +} diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..6199678 --- /dev/null +++ b/config/config.go @@ -0,0 +1,49 @@ +package config + +import ( + "encoding/json" + "flag" + "log" + "os" +) + +type Configuration struct { + Db struct { + Ip string `json:"DbIp"` + Port string `json:"DbPort"` + Name string `json:"DbName"` + User string `json:"DbUser"` + Password string `json:"DbPassword"` + } + + Listen struct { + Ip string `json:"HttpIp"` + Port string `json:"HttpPort"` + } + + Template struct { + BaseName string `json:"BaseTemplateName"` + } +} + +// LoadConfig loads and returns a configuration struct +func LoadConfig() Configuration { + c := flag.String("c", "env.json", "Path to the json configuration file") + flag.Parse() + file, err := os.Open(*c) + if err != nil { + log.Fatal("Unable to open config JSON file: ", err) + } + + defer file.Close() + + // Decode json config file to Configuration struct named config + decoder := json.NewDecoder(file) + Config := Configuration{} + err = decoder.Decode(&Config) + if err != nil { + log.Fatal("Unable to decode config JSON file: ", err) + } + + return Config +} diff --git a/env_example.json b/env_example.json new file mode 100644 index 0000000..701bf63 --- /dev/null +++ b/env_example.json @@ -0,0 +1,16 @@ +{ + "Db": { + "DbIp": "127.0.0.1", + "DbPort": "5432", + "DbName": "database", + "DbUser": "user", + "DbPassword": "password" + }, + "Listen": { + "HttpIp": "127.0.0.1", + "HttpPort": "8090" + }, + "Template": { + "BaseTemplateName": "templates/base.html" + } +} \ No newline at end of file