-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathsample_db.go
86 lines (67 loc) · 1.43 KB
/
sample_db.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"log"
"os"
"gopkg.in/mgo.v2"
)
var DB *mgo.Database
func MustConnectMongo() {
if err := ConnectMongo(); err != nil {
panic(err)
}
}
func InitDB() {
defer func() {
if e := recover(); e != nil {
log.Println(e)
}
}()
Insert(&Person{Name: "Ale", Phone: "+55 53 1234 4321"})
Insert(&Person{Name: "Cla", Phone: "+66 33 1234 5678"})
}
var (
username string
password string
host string
port string
instance string
)
func Config() {
username = os.Getenv("MONGODB_USERNAME")
password = os.Getenv("MONGODB_PASSWORD")
host = os.Getenv("MONGODB_PORT_27017_TCP_ADDR")
if len(host) == 0 {
host = "localhost"
}
port = os.Getenv("MONGODB_PORT_27017_TCP_PORT")
if len(port) == 0 {
port = "27017"
}
instance = os.Getenv("MONGODB_INSTANCE_NAME")
}
func ConnectMongo() error {
conn := ""
if len(username) > 0 {
conn += username
if len(password) > 0 {
conn += ":" + password
}
conn += "@"
}
conn += fmt.Sprintf("%s:%s/%s", host, port, instance)
session, err := mgo.Dial(conn)
if err != nil {
return err
}
DB = session.DB(instance)
peopleC = DB.C("people")
return nil
}
func Drop() {
// Drop Collection
err := peopleC.DropCollection()
if err != nil {
log.Println(err)
}
}