go-jwtserver/middleware/postgres.go

52 lines
1.0 KiB
Go
Raw Permalink Normal View History

2020-07-16 13:56:57 +02:00
package middleware
2020-07-16 10:51:50 +02:00
import (
"fmt"
"os"
2020-07-21 11:08:01 +02:00
"github.com/gofrs/uuid"
2020-07-16 10:51:50 +02:00
"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)
}
2020-07-22 10:14:13 +02:00
username := os.Getenv("jwt_db_user")
password := os.Getenv("jwt_db_pass")
dbName := os.Getenv("jwt_db_name")
dbHost := os.Getenv("jwt_db_host")
2020-07-16 10:51:50 +02:00
2020-07-22 10:14:13 +02:00
dbURI := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, username, dbName, password) //Build connection string
fmt.Println(dbURI)
2020-07-16 10:51:50 +02:00
2020-07-22 10:14:13 +02:00
conn, err := gorm.Open("postgres", dbURI)
2020-07-16 10:51:50 +02:00
if err != nil {
fmt.Print(err)
}
db = conn
db.Debug().AutoMigrate(&Account{}) //Database migration
}
2020-07-22 10:14:13 +02:00
//GetDB returns a handle to the DB object
2020-07-16 10:51:50 +02:00
func GetDB() *gorm.DB {
return db
}
2020-07-21 11:08:01 +02:00
// 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)
}