database setup

This commit is contained in:
2024-02-21 13:55:57 -06:00
parent b24e476f9c
commit 06094f05b3
5 changed files with 43 additions and 7 deletions

3
.gitignore vendored
View File

@@ -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

BIN
go-crud

Binary file not shown.

21
initializers/database.go Normal file
View File

@@ -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")
}
}

View File

@@ -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")
}
}

10
main.go
View File

@@ -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() {