forked from couchbaselabs/devguide-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.go
47 lines (38 loc) · 1.16 KB
/
counter.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
package main
import (
"fmt"
"gopkg.in/couchbase/gocb.v1"
)
// bucket reference - reuse as bucket reference in the application
var bucket *gocb.Bucket
func main() {
// Connect to Cluster
cluster, err := gocb.Connect("couchbase://127.0.0.1")
if err != nil {
fmt.Println("ERROR CONNECTING TO CLUSTER:", err)
}
// Open Bucket
bucket, err = cluster.OpenBucket("travel-sample", "")
if err != nil {
fmt.Println("ERROR OPENING BUCKET:", err)
}
// Create a document and assign it to 10 - counter works atomically by
// first creating a document if it doesn't exist. If it exists, the
// same method will increment/decrement per the "delta" parameter
key := "goDevguideExampleCounter"
curKeyValue, _, err := bucket.Counter(key, 2, 10, 0)
if err != nil {
fmt.Println("ERROR CREATING KEY:", err)
}
// Should Print 10
fmt.Println("Initialized Counter:", curKeyValue)
// Issue same operation, increment value by 2, to 12
curKeyValue, _, err = bucket.Counter(key, 2, 10, 0)
if err != nil {
fmt.Println("ERROR CREATING KEY:", err)
}
// Should Print 12
fmt.Println("Incremented Counter:", curKeyValue)
// Exiting
fmt.Println("Example Successful - Exiting")
}