From 2cdbbd574540c6c0c512e89f5a01ea5eee3da891 Mon Sep 17 00:00:00 2001 From: Nedim Date: Tue, 5 Sep 2023 11:37:03 +0200 Subject: [PATCH] Added environment variables --- config/config.go | 46 +++++++++++++++++++++++++++++ config/helpers.go | 73 ++++++++++++++++++++++++++++++++++++++++++++++ config/models.go | 26 +++++++++++++++++ env-example | 9 ++++++ go.mod | 1 + go.sum | 2 ++ main.go | 59 ++++++++++++++++++------------------- shared/database.go | 31 +++++++------------- 8 files changed, 196 insertions(+), 51 deletions(-) create mode 100644 config/config.go create mode 100644 config/helpers.go create mode 100644 config/models.go create mode 100644 env-example diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..69e6155 --- /dev/null +++ b/config/config.go @@ -0,0 +1,46 @@ +package config + +import ( + "log" + + "github.com/joho/godotenv" +) + +// AppConfig contains application configuration +var AppConfig Config + +// Load application configuration +func Load() error { + + // load .env file + err := godotenv.Load() + + if err != nil { + log.Println(".env file not presented. Retrieving configuration from environment variables") + } + + AppConfig = Config{ + + Service: Service{ + // 9000 DEFAULT FOR DEV ENVIRONMENT + Port: getEnv("NOVATECH_SERVICE_PORT", "9000"), + Environment: getEnv("NOVATECH_SERVICE_ENVIRONMENT", "DEV"), + }, + AdminService: Service{ + // 8080 DEFAULT FOR DEV ENVIRONMENT + Port: getEnv("NOVATECH_ADMIN_SERVICE_PORT", "8080"), + Environment: getEnv("NOVATECH_ADMIN_SERVICE_ENVIRONMENT", "DEV"), + }, + Database: Database{ + UserName: mustGetEnv("NOVATECH_DATABASE_USERNAME"), + Password: mustGetEnv("NOVATECH_DATABASE_PASSWORD"), + DatabaseName: mustGetEnv("NOVATECH_DATABASE_NAME"), + HostName: mustGetEnv("NOVATECH_DATABASE_ADDRESS"), + Port: mustGetEnv("NOVATECH_DATABASE_PORT"), + + }, + + } + + return nil +} diff --git a/config/helpers.go b/config/helpers.go new file mode 100644 index 0000000..076099a --- /dev/null +++ b/config/helpers.go @@ -0,0 +1,73 @@ +package config + +import ( + "log" + "os" + "strconv" +) + +// getEnv returns value for give key from environment +// if key is not present in environment it returns defaultValue +func getEnv(key, defaultValue string) string { + v := os.Getenv(key) + if len(v) > 0 { + return v + } + return defaultValue +} + +// getEnvInt returns integer value for give key from environment +// if key is not present in environment it returns defaultValue +// if key cannot be parsed to integer function will panic +func getEnvInt(key string, defaultValue int) int { + v := os.Getenv(key) + if len(v) == 0 { + return defaultValue + } + + valInteger, err := strconv.Atoi(v) + if err != nil { + log.Fatalf("variable `%s` cannot be parsed to INTEGER", key) + } + + return valInteger +} + +// getEnvInt returns integer value for give key from environment +// if key is not present in environment it returns defaultValue +// if key cannot be parsed to integer function will panic +func getEnvBoolWithDefault(key string, defaultValue bool) bool { + v := os.Getenv(key) + if len(v) == 0 { + return defaultValue + } + + val, err := strconv.ParseBool(v) + if err != nil { + log.Fatalf("variable `%s` cannot be parsed to BOOL", key) + } + + return val +} + +// getEnv extracts the bool value from environment variable +func getEnvBool(env string) bool { + envVal := mustGetEnv(env) + value, err := strconv.ParseBool(envVal) + + if err != nil { + value = false + } + + return value +} + +// mustGetEnv returns value for give key from environment +// if key is not present in environment function will panic +func mustGetEnv(key string) string { + v := os.Getenv(key) + if len(v) == 0 { + log.Fatalf(" variable `%s` is not present in ENVIRONMENT", key) + } + return v +} diff --git a/config/models.go b/config/models.go new file mode 100644 index 0000000..f0de75e --- /dev/null +++ b/config/models.go @@ -0,0 +1,26 @@ +package config + +// Config stores application configuration +type Config struct { + Service Service + AdminService Service + Database Database +} + + +// Service contains configuration for service +type Service struct { + Port string + Environment string + WebPageURL string +} + +// Database configuration +type Database struct { + UserName string + Password string + DatabaseName string + HostName string + Port string +} + diff --git a/env-example b/env-example new file mode 100644 index 0000000..f624e85 --- /dev/null +++ b/env-example @@ -0,0 +1,9 @@ +NOVATECH_SERVICE_PORT=9000 +NOVATECH_SERVICE_ENVIRONMENT=DEV +NOVATECH_ADMIN_SERVICE_PORT=8080 +NOVATECH_ADMIN_SERVICE_ENVIRONMENT=DEV +NOVATECH_DATABASE_USERNAME=username +NOVATECH_DATABASE_PASSWORD=password +NOVATECH_DATABASE_NAME=dbname +NOVATECH_DATABASE_ADDRESS=localhost +NOVATECH_DATABASE_PORT=5432 \ No newline at end of file diff --git a/go.mod b/go.mod index 3f5c682..b79cbb1 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gin-gonic/gin v1.9.1 github.com/jinzhu/gorm v1.9.16 + github.com/joho/godotenv v1.5.1 github.com/mattn/go-sqlite3 v1.14.0 github.com/qor/admin v1.2.0 ) diff --git a/go.sum b/go.sum index 7d9e84c..ba1ba73 100644 --- a/go.sum +++ b/go.sum @@ -75,6 +75,8 @@ github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/ github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E= github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= diff --git a/main.go b/main.go index 727845f..7778256 100644 --- a/main.go +++ b/main.go @@ -2,11 +2,13 @@ package main import ( "fmt" + "log" "net/http" + "novatech/config" "novatech/models" + "novatech/routes" + "novatech/shared" - "github.com/VoidArtanis/go-rest-boilerplate/routes" - "github.com/VoidArtanis/go-rest-boilerplate/shared" "github.com/gin-gonic/gin" "github.com/jinzhu/gorm" "github.com/qor/admin" @@ -15,45 +17,40 @@ import ( var DB *gorm.DB func main() { - // Initialize the database connection - DB, err := gorm.Open("postgres", "host=localhost user=postgres dbname=postgres sslmode=disable password=root") + + + // LOAD APPLICATION CONFIGURATION + err := config.Load() if err != nil { - fmt.Println("Error opening database:", err) - return + log.Fatal(err) } - defer DB.Close() - - // AutoMigrate the User model - DB.AutoMigrate(&models.User{}) - - // Initialize Admin interface - Admin := admin.New(&admin.AdminConfig{DB: DB}) - - // Allow Admin to manage User resource - Admin.AddResource(&models.User{}) - - // Initialize HTTP request multiplexer - mux := http.NewServeMux() - - // Mount admin interface to mux - Admin.MountTo("/admin", mux) - - // Start the admin server in a separate goroutine - go func() { - fmt.Println("Admin server listening on :9000") - http.ListenAndServe(":9000", mux) - }() // Db Connect and Close shared.Init() defer shared.CloseDb() + // Initialize Admin interface + Admin := admin.New(&admin.AdminConfig{DB: shared.GetDb()}) + // Allow Admin to manage User resource + Admin.AddResource(&models.User{}) + // Initialize HTTP request multiplexer + mux := http.NewServeMux() + // Mount admin interface to mux + Admin.MountTo("/admin", mux) + + // Start the admin server in a separate goroutine + go func() { + port := config.AppConfig.Service.Port + fmt.Println("Admin server listening on :" + port) + http.ListenAndServe(":" + port, mux) + }() + // Initialize Gin r := gin.Default() routes.InitRouter(r) - // Start the Gin server on another port - fmt.Println("Application server listening on :8080") - r.Run(":8080") + port := config.AppConfig.AdminService.Port + fmt.Println("Application server listening on :" + port) + r.Run(":" + port) } diff --git a/shared/database.go b/shared/database.go index fd3a206..bc5d9b6 100644 --- a/shared/database.go +++ b/shared/database.go @@ -1,43 +1,34 @@ -/** - * Created by VoidArtanis on 10/22/2017 - */ - package shared import ( "fmt" + "novatech/config" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" ) -//import _ "github.com/jinzhu/gorm/dialects/mysql" -// import _ "github.com/jinzhu/gorm/dialects/sqlite" -// import _ "github.com/jinzhu/gorm/dialects/mssql" var db *gorm.DB var err error -/* -dbType can be 'MySql', 'Postrges', '' - */ + func Init() { - ////MySQL - //db, err = gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local") + host := config.AppConfig.Database.HostName + user := config.AppConfig.Database.UserName + port := config.AppConfig.Database.Port + dbName := config.AppConfig.Database.DatabaseName + password := config.AppConfig.Database.Password + + dbString:= fmt.Sprintf("postgres, host=%s:%s user=%s dbname=%s sslmode=disable password=%s",host,port,user,dbName,password) //PostgreSQL - db, err = gorm.Open("postgres", "host=myhost user=gorm dbname=gorm sslmode=disable password=root") - - ////SQLite3 - //db, err = gorm.Open("sqlite3", "/tmp/gorm.db") - // - ////SQL Server - //db, err = gorm.Open("mssql", "sqlserver://username:password@localhost:1433?database=dbname") + db, err = gorm.Open(dbString) if err != nil { fmt.Println(err) } - + //TODO AUTOMIGRATE models once we have them //db.AutoMigrate(&models.Person{}) } -- 2.47.3