-
Notifications
You must be signed in to change notification settings - Fork 40
/
main.go
87 lines (70 loc) · 1.71 KB
/
main.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
87
package bongo
import (
"errors"
"fmt"
"github.com/globalsign/mgo"
)
type Config struct {
ConnectionString string
Database string
DialInfo *mgo.DialInfo
}
// var EncryptionKey [32]byte
// var EnableEncryption bool
type Connection struct {
Config *Config
Session *mgo.Session
// collection []Collection
Context *Context
}
// Create a new connection and run Connect()
func Connect(config *Config) (*Connection, error) {
conn := &Connection{
Config: config,
Context: &Context{},
}
err := conn.Connect()
return conn, err
}
// Connect to the database using the provided config
func (m *Connection) Connect() (err error) {
defer func() {
if r := recover(); r != nil {
// panic(r)
// return
if e, ok := r.(error); ok {
err = e
} else if e, ok := r.(string); ok {
err = errors.New(e)
} else {
err = errors.New(fmt.Sprint(r))
}
}
}()
if m.Config.DialInfo == nil {
if m.Config.DialInfo, err = mgo.ParseURL(m.Config.ConnectionString); err != nil {
panic(fmt.Sprintf("cannot parse given URI %s due to error: %s", m.Config.ConnectionString, err.Error()))
}
}
session, err := mgo.DialWithInfo(m.Config.DialInfo)
if err != nil {
return err
}
m.Session = session
m.Session.SetMode(mgo.Monotonic, true)
return nil
}
// CollectionFromDatabase ...
func (m *Connection) CollectionFromDatabase(name string, database string) *Collection {
// Just create a new instance - it's cheap and only has name and a database name
return &Collection{
Connection: m,
Context: m.Context,
Database: database,
Name: name,
}
}
// Collection ...
func (m *Connection) Collection(name string) *Collection {
return m.CollectionFromDatabase(name, m.Config.Database)
}