-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdk-connection-go.go
More file actions
116 lines (100 loc) · 2.45 KB
/
sdk-connection-go.go
File metadata and controls
116 lines (100 loc) · 2.45 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Couchbase SDK connection singleton — Go
// Copy and adapt for your application.
//
// Dependencies:
// go get github.com/couchbase/gocb/v2
package couchbase
import (
"fmt"
"sync"
"time"
"github.com/couchbase/gocb/v2"
)
// --- Configuration ---
const (
cbHost = "localhost" // or "cb.xxxxx.cloud.couchbase.com" for Capella
cbUser = "app-service-user"
cbPassword = "AppSecret123!"
cbBucket = "myapp"
cbScope = "_default"
cbCollection = "_default"
)
var (
once sync.Once
cluster *gocb.Cluster
collection *gocb.Collection
)
// GetCollection returns the singleton Collection, initializing the cluster on first call.
func GetCollection() *gocb.Collection {
once.Do(func() {
if err := init_(); err != nil {
panic(fmt.Sprintf("couchbase init failed: %v", err))
}
})
return collection
}
// GetCluster returns the singleton Cluster (needed for queries and transactions).
func GetCluster() *gocb.Cluster {
GetCollection() // ensures cluster is initialized
return cluster
}
func init_() error {
// Use "couchbases://" for TLS (required for Capella, recommended for production)
c, err := gocb.Connect("couchbase://"+cbHost, gocb.ClusterOptions{
Username: cbUser,
Password: cbPassword,
TimeoutsConfig: gocb.TimeoutsConfig{
ConnectTimeout: 10 * time.Second,
KVTimeout: 2500 * time.Millisecond,
QueryTimeout: 75 * time.Second,
SearchTimeout: 75 * time.Second,
},
})
if err != nil {
return err
}
if err = c.WaitUntilReady(10*time.Second, nil); err != nil {
return err
}
cluster = c
collection = c.Bucket(cbBucket).Scope(cbScope).Collection(cbCollection)
return nil
}
// Close releases cluster resources. Call on application shutdown.
func Close() {
if cluster != nil {
cluster.Close(nil)
}
}
// --- Usage example ---
func Example() {
col := GetCollection()
c := GetCluster()
// KV upsert
_, err := col.Upsert("doc_1", map[string]interface{}{"type": "example", "value": 42}, nil)
if err != nil {
panic(err)
}
// KV get
result, err := col.Get("doc_1", nil)
if err != nil {
panic(err)
}
var doc map[string]interface{}
result.Content(&doc)
fmt.Println(doc)
// SQL++ query
rows, err := c.Query(
"SELECT * FROM `myapp`._default._default WHERE type = $type LIMIT 5",
&gocb.QueryOptions{NamedParameters: map[string]interface{}{"type": "example"}},
)
if err != nil {
panic(err)
}
for rows.Next() {
var row interface{}
rows.Row(&row)
fmt.Println(row)
}
Close()
}