diff --git a/.gitignore b/.gitignore index adf8f72..0dc62a2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ # ---> Go # If you prefer the allow list template instead of the deny list, see community template: # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# Manual +go-crud +.env # # Binaries for programs and plugins *.exe diff --git a/go-crud b/go-crud index ea99fe6..0782337 100755 Binary files a/go-crud and b/go-crud differ diff --git a/initializers/database.go b/initializers/database.go new file mode 100644 index 0000000..c3aaa99 --- /dev/null +++ b/initializers/database.go @@ -0,0 +1,21 @@ +package initializers + +import ( + "log" + "os" + + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +var DB *gorm.DB + +func ConnectToDB() { + var err error + dsn := os.Getenv("DB_URL") + DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) + + if err != nil { + log.Fatal("Fail to connect to DB") + } +} diff --git a/initializers/loadEnvVariables.go b/initializers/loadEnvVariables.go new file mode 100644 index 0000000..56c021d --- /dev/null +++ b/initializers/loadEnvVariables.go @@ -0,0 +1,16 @@ +package initializers + +import ( + "log" + + "github.com/joho/godotenv" +) + +func LoadEnvVariables() { + err := godotenv.Load() + + if err != nil { + log.Fatal("Error loading .env file") + } + +} diff --git a/main.go b/main.go index 970cbb9..1827b09 100644 --- a/main.go +++ b/main.go @@ -1,19 +1,15 @@ package main import ( - "log" "net/http" + "gitea.sitodosi.com/betology/go-crud/initializers" "github.com/gin-gonic/gin" - "github.com/joho/godotenv" ) func init() { - err := godotenv.Load() - if err != nil { - log.Fatal("Error loading .env file") - } - + initializers.LoadEnvVariables() + initializers.ConnectToDB() } func main() {