52 lines
1.0 KiB
Go
52 lines
1.0 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/gofrs/uuid"
|
|
"github.com/jinzhu/gorm"
|
|
_ "github.com/jinzhu/gorm/dialects/postgres"
|
|
"github.com/joho/godotenv"
|
|
)
|
|
|
|
var db *gorm.DB //database
|
|
|
|
func init() {
|
|
|
|
e := godotenv.Load() //Load .env file
|
|
if e != nil {
|
|
fmt.Print(e)
|
|
}
|
|
|
|
username := os.Getenv("jwt_db_user")
|
|
password := os.Getenv("jwt_db_pass")
|
|
dbName := os.Getenv("jwt_db_name")
|
|
dbHost := os.Getenv("jwt_db_host")
|
|
|
|
dbURI := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, username, dbName, password) //Build connection string
|
|
fmt.Println(dbURI)
|
|
|
|
conn, err := gorm.Open("postgres", dbURI)
|
|
if err != nil {
|
|
fmt.Print(err)
|
|
}
|
|
|
|
db = conn
|
|
db.Debug().AutoMigrate(&Account{}) //Database migration
|
|
}
|
|
|
|
//GetDB returns a handle to the DB object
|
|
func GetDB() *gorm.DB {
|
|
return db
|
|
}
|
|
|
|
// BeforeCreate will set a UUID rather than numeric ID.
|
|
func (accont *Account) BeforeCreate(scope *gorm.Scope) error {
|
|
uuid, err := uuid.NewV4()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return scope.SetColumn("ID", uuid)
|
|
}
|