forked from cassiobotaro/60-days-of-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsingleton.go
68 lines (61 loc) · 1.56 KB
/
singleton.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"fmt"
"log"
"os"
"sync"
"github.com/jmoiron/sqlx"
// Used pg drive on sqlx
_ "github.com/lib/pq"
)
var (
db *sqlx.DB
once sync.Once
)
// Singleton
// In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object.
// This is useful when exactly one object is needed to coordinate actions across the system.
// https://en.wikipedia.org/wiki/Singleton_pattern
// http://marcio.io/2015/07/singleton-pattern-in-go/
// Set database config
// export PGUSER=postgres
// export PGDB=postgres
// export PGHOST=localhost
// export PGPORT=5432
// Run postgresql inside a container
// docker run -d -p 5432:5432 postgres:latest
// MustGetConnection returns database connection
func MustGetConnection() *sqlx.DB {
once.Do(func() {
pguser := os.Getenv("PGUSER")
pgdb := os.Getenv("PGDB")
pghost := os.Getenv("PGHOST")
pgport := os.Getenv("PGPORT")
pgpass := os.Getenv("PGPASS")
dbURI := fmt.Sprintf("user=%s dbname=%s host=%s port=%v sslmode=disable", pguser, pgdb, pghost, pgport)
if pgpass != "" {
dbURI += " password=" + pgpass
}
var err error
db, err = sqlx.Connect("postgres", dbURI)
if err != nil {
panic(fmt.Sprintf("Unable to connection to database: %v\n", err))
}
db.SetMaxIdleConns(10)
db.SetMaxOpenConns(10)
})
return db
}
func main() {
// Verify if connection is ok
conn := MustGetConnection()
err := conn.Ping()
if err != nil {
log.Fatal(err)
}
fmt.Println("Successfully connected ✓")
err = conn.Close()
if err != nil {
log.Fatal(err)
}
}