-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (62 loc) · 1.37 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 main
import (
"fmt"
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type State struct {
CustomerId string
CreatedOn time.Time
CreatedBy string
Description string
}
type DataStore struct {
session *mgo.Session
err error
}
func (ds *DataStore) getCol(collectionName string) *mgo.Collection {
ds.session, ds.err = mgo.Dial("localhost:27017")
if ds.err != nil {
panic(ds.err)
}
return ds.session.DB("c3po_db").C(collectionName)
}
func (ds *DataStore) GetAll() []State {
var states []State
ds.err = ds.getCol("state").Find(bson.M{}).All(&states)
if ds.err != nil {
panic(ds.err)
}
ds.session.Close()
return states
}
func (ds *DataStore) GetById(customerId string) State {
var state State
ds.err = ds.getCol("state").Find(bson.M{"customerId": customerId}).One(&state)
if ds.err != nil {
panic(ds.err)
}
ds.session.Close()
return state
}
func (ds *DataStore) CreateOrUpdate(state State) bool {
_, ds.err = ds.getCol("state").Upsert(
bson.M{"customerId": state.CustomerId},
bson.M{"$set": state})
if ds.err != nil {
panic(ds.err)
} else {
ds.session.Close()
return true
}
ds.session.Close()
return false
}
func main() {
ds := DataStore{}
state := State{CustomerId: "3", CreatedOn: time.Now(), CreatedBy: "Ivo", Description: "6"}
ds.CreateOrUpdate(state)
fmt.Println(ds.GetById("3"))
fmt.Println(ds.GetAll())
}