i have package config.go in this my code
package config
import (
"fmt"
logger "github.com/sirupsen/logrus"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func DatabaseConnect() *gorm.DB {
DBURL := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s", pkg.GodotEnv("DB_HOST"), pkg.GodotEnv("DB_PORT"), pkg.GodotEnv("DB_USER"), pkg.GodotEnv("DB_NAME"), pkg.GodotEnv("DB_PASSWORD"))
db, err := gorm.Open(postgres.Open(DBURL), &gorm.Config{})
if err != nil {
defer logger.Info("Database connection failed")
logger.Fatal(err)
return nil
}
return db
}
and main.go
func main() {
e := echo.New()
db := config.DatabaseConnect()
middleware.WebSecurityConfig(e)
routes.NewRoute(db, e)
e.Logger.Fatal(e.Start(":8080"))
}
I want to create a dynamic routing like the example below :
server.Initialize(os.Getenv("DB_DRIVER"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_PORT"), os.Getenv("DB_HOST"), os.Getenv("DB_NAME"))
server.Run(":" + os.Getenv("PORT"))
how to create dinamic port server ? thanks
Check this out: https://github.com/joho/godotenv.
Add your application configuration to your .env file in the root of your project:
DB_DRIVER=mysql
DB_USER=root
...
Then in your Go app you can do something like:
package main
import (
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
driver:= os.Getenv("DB_DRIVER")
user:= os.Getenv("DB_USER")
// todo
}