-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
48 lines (39 loc) · 902 Bytes
/
db.go
File metadata and controls
48 lines (39 loc) · 902 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"fmt"
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
var Database *gorm.DB
func init() {
var err error
if url := os.Getenv("DATABASE_URL"); len(url) > 0 {
Database, err = gorm.Open("postgres", url)
} else {
connString := fmt.Sprintf("user=%s dbname=%s password=%s sslmode=disable", os.Getenv("DB_USER"), os.Getenv("DB_NAME"), os.Getenv("DB_PW"))
Database, err = gorm.Open("postgres", connString)
}
if err != nil {
panic(err)
}
}
// DB is middleware to get the database
func DB() gin.HandlerFunc {
return func(c *gin.Context) {
if err := Database.DB().Ping(); err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Set("db", Database)
}
}
func GetDB(c *gin.Context) *gorm.DB {
db, ok := c.Get("db")
if !ok {
panic("couldn't get database")
}
return db.(*gorm.DB)
}