### Clone the Golang Quickstart Repository Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/sample-application.adoc Clone the example project from GitHub to start building your REST API. ```console $ git clone https://github.com/couchbase-examples/golang-quickstart.git ``` -------------------------------- ### Install Couchbase Go SDK Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/platform-help.adoc Use `go get` to download the SDK. This command requires an initialized Go module with a `go.mod` file in your working directory. ```bash $ go get github.com/couchbase/gocb/v2@v2.6.0 ``` -------------------------------- ### Go XATTR Example Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/concept-docs/pages/xattr.adoc Demonstrates basic usage of Extended Attributes (XATTR) in Go, including setting and getting attributes. ```golang func main() { // Connect to Couchbase cluster, err := gocb.Connect(os.Getenv("COUCHBASE_CONN_STR"), gocb.ClusterOptions{ Username: "Administrator", Password: "password", }) if err != nil { panic(err) } // Get a handle for our bucket. bucket, err := cluster.Bucket("travel-sample") if err != nil { panic(err) } // Use the example document. collection := bucket.DefaultCollection() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // Set some extended attributes. _, err = collection.Upsert( "airline_10001", map[string]interface{}{"name": "Example Airline", "iata": "EXA"}, gocb.UpsertOptions{ PersistTo: gocb.PersistTo(1), // Set xattrs XAttrs: map[string]interface{}{ "protected": map[string]interface{}{"foo": "bar"}, "private": map[string]interface{}{"baz": "qux"}, }, }, ) if err != nil { panic(err) } // Get the document with its extended attributes. res, err := collection.Get( "airline_10001", gocb.GetOptions{ // Request xattrs WithXattrs: true, }, ) if err != nil { panic(err) } // Print the document body and xattrs. fmt.Printf("Document Body: %v\n", res.Content) fmt.Printf("Protected XAttrs: %v\n", res. এক্সattrs["protected"]) fmt.Printf("Private XAttrs: %v\n", res. এক্সattrs["private"]) // Remove the document. _, err = collection.Remove("airline_10001") if err != nil { panic(err) } // Disconnect cluster.Close(nil) } ``` -------------------------------- ### Install Couchbase Go SDK v2 Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/project-docs/pages/sdk-full-installation.adoc Use `go get` to download the latest version of the Couchbase Go SDK v2. This command requires an initialized Go module with a `go.mod` file in your working directory. ```bash $ go get github.com/couchbase/gocb/v2@v{sdk_current_version} ``` -------------------------------- ### Install Couchbase Go SDK Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/overview.adoc Command to install the Couchbase Go SDK version 2 using the Go package manager. ```console $ go get github.com/couchbase/gocb/v2 ``` -------------------------------- ### Install Go Couchbase Encryption Library Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/encrypting-using-sdk.adoc Fetch the Go Couchbase Encryption library using the go get command. This library is an optional dependency. ```console $ go get github.com/couchbase/gocbencryption/v2.0.0 ``` -------------------------------- ### Run the Golang Application Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/sample-application.adoc Execute the Go application to start the Gin Web Framework server. ```console go run main.go ``` -------------------------------- ### Example Course Record JSON Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/student-record-developer-tutorial.adoc This is an example of a course record document retrieved from the `course-record-collection`. ```json [ { "course-name": "art history", "credit-points": 100, ``` -------------------------------- ### Update Document Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/start-using-sdk.adoc Updates an existing document. This example demonstrates a typical workflow of getting a document, modifying its content, and then updating it. ```go // Get the document res, err := collection.Get("documentKey", nil) if err != nil { panic(err) } // Unmarshal the document content var myDoc map[string]interface{} err = res.Content(&myDoc) if err != nil { panic(err) } // Modify the document myDoc["value"] = 789 // Replace the document using the CAS value _, err = collection.Replace("documentKey", myDoc, &couchbase.ReplaceOptions{ CAS: res.Cas, }) if err != nil { panic(err) } ``` -------------------------------- ### Vector Search Combination Example (Go) Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/overview.adoc Shows how to combine vector search with full-text search (FTS) queries in Go. This enables sophisticated search capabilities for AI-driven applications. ```go searchReq := gocb.NewSearchRequest(). Add([]gocb.SearchQuery{gocb.NewVectorSearchQuery(vector).SetField("embedding").SetK(3)}). Add([]gocb.SearchQuery{gocb.NewFtsQuery("my_fts_index", "search term")}) resultSet, err := collection.Search("my_search_index", searchReq, nil) if err != nil { panic(err) } for resultSet.Next() { var row map[string]interface{ } resultSet.Row(&row) fmt.Println(row) } ``` -------------------------------- ### Query Consistency Example (Go) Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/overview.adoc Illustrates how to set query consistency levels for N1QL queries in Go. Choose the appropriate consistency for your application's needs, balancing performance and data freshness. ```go query := gocb.N1qlQuery("SELECT " + bucketName + " .name FROM `" + bucketName + "` WHERE LOWER(name) = LOWER($1)"). WithConsistency(gocb.QueryScanPlus) rows, err := bucket.Query(query, gocb.QueryOptions{ScanConsistency: gocb.QueryScanPlus, AdHoc: true}, "alice") if err != nil { panic(err) } defer rows.Close() ``` -------------------------------- ### Enhanced KV Durability Example (Go) Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/overview.adoc Demonstrates how to use enhanced durability options for Key-Value operations in Go. This is useful when strong consistency guarantees are required for data operations. ```go err := collection.Upsert("myKey", map[string]interface{}{"name": "Alice"}, nil) if err != nil { panic(err) } ``` -------------------------------- ### Another Course Record JSON Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/student-record-developer-tutorial.adoc An example of a course record, illustrating the data fields for a different course. ```json { "course-id": "GRAPHIC-DESIGN-00001", "course-name": "graphic design", "faculty": "media and communication", "credit-points" : 200 } ``` -------------------------------- ### Real-World Insert with Retry Wrapper Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/error-handling.adoc This example demonstrates a real-world approach to error handling by creating a wrapper function for insert operations. It includes a basic retry strategy for handling transient errors. ```go func doInsertReal(collection *gocb.Collection, id string, value interface{}) error { for i := 0; i < 3; i++ { _, err := collection.Insert(id, value) if err == nil { return nil // Success } if errors.Is(err, gocb.ErrDocumentExists) { return nil // Already exists, consider it a success for this wrapper } if errors.Is(err, gocb.ErrTimeout) || errors.Is(err, gocb.ErrDurabilityAmbiguous) { log.Printf("Attempt %d: Transient error, retrying insert for %s...", i+1, id) time.Sleep(time.Duration(i+1) * 100 * time.Millisecond) // Naive backoff continue } return fmt.Errorf("failed to insert document %s after %d attempts: %w", id, i+1, err) } return fmt.Errorf("failed to insert document %s after multiple retries", id) } // Usage: // err := doInsertReal(collection, "my_real_key", map[string]interface{}{"data": "some value"}) // if err != nil { // log.Printf("Operation failed: %v", err) // // Handle final failure, e.g., display message to user, log for review // } ``` -------------------------------- ### Install OpenTelemetry Dependencies Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/observability-tracing.adoc Add the Couchbase OpenTelemetry module and OTLP trace exporter as dependencies for exporting tracing telemetry. ```console go get github.com/couchbase/gocb-opentelemetry go get go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc go get go.opentelemetry.io/otel/sdk/trace ``` -------------------------------- ### Configure OpenTelemetry Metrics Exporter Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/observability-metrics.adoc Integrate the SDK with OpenTelemetry by configuring an exporter to send metrics. This example uses gRPC to send metrics to an OTLP endpoint. ```go import ( "context" "time" "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc" "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/metric/metricdata" "go.opentelemetry.io/otel/sdk/metric/metricdata/aggregation" "github.com/couchbase/gocb/v2" "github.com/couchbase/gocb-opentelemetry" ) func main() { ctx := context.Background() // Create an OTLP exporter exporter, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithInsecure()) if err != nil { panic(err) } // Create a meter provider with the exporter and a periodic reader reader := metric.NewPeriodicReader(exporter, metric.WithInterval(10*time.Second)) meterProvider := metric.NewMeterProvider( metric.WithReader(reader), ) // Connect to Couchbase with OpenTelemetry metrics enabled cluster, err := gocb.Connect("couchbase://localhost", gocb.ClusterOptions{ Authenticator: gocb.PasswordAuthenticator{ Username: "Administrator", Password: "password", }, Metrics: gocb_opentelemetry.NewMetrics(meterProvider), }) if err != nil { panic(err) } // Use the cluster as usual _ = cluster.Bucket("default") // ... application logic ... // Shutdown the meter provider and disconnect gracefully defer func() { _ = meterProvider.Shutdown(ctx) _ = cluster.Close(ctx) }() } ``` -------------------------------- ### Connect to Couchbase Capella Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/managing-connections.adoc Use this method to establish a connection to a Couchbase Capella cluster. The client certificate is included in the SDK installation. ```golang cluster, err := gocb.Connect(os.Getenv("COUCHBASE_CAPELLA_CONNECTION_STRING"), gocb.ClusterOptions{ Authenticator: gocb.PasswordAuthenticator{ Username: os.Getenv("COUCHBASE_CAPELLA_USERNAME"), Password: os.Getenv("COUCHBASE_CAPELLA_PASSWORD"), }, }) ``` -------------------------------- ### Intermix Key-Value and Query Operations in Transaction Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/distributed-acid-transactions-from-the-sdk.adoc Shows an example of mixing key-value insert operations with SELECT queries within a single transaction. This highlights how staged mutations are visible to subsequent queries in the same transaction. ```go var doc myStruct err := tx.Insert(ctx, "kvDocID", doc) if err != nil { // Handle error } rows, err := tx.Query(ctx, "SELECT * FROM `travel-sample` WHERE META().id = $1", gocb.QueryOptions{ PositionalParameters: []interface{}{"kvDocID"}, }) if err != nil { // Handle error } var result map[string]interface{} err = rows.One(ctx, &result) if err != nil { // Handle error } ``` -------------------------------- ### Build Docker Image Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/sample-application.adoc Build the Docker image for the application using the provided Dockerfile. This command tags the image as 'couchbase-gin-gonic-quickstart'. ```console $ docker build -t couchbase-gin-gonic-quickstart . ``` -------------------------------- ### Navigate to the Project Directory Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/sample-application.adoc Change your current directory to the cloned project folder. ```console $ cd golang-quickstart ``` -------------------------------- ### Example JSON Output Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/observability-tracing.adoc This is an example of the JSON blob emitted by the default ThresholdLoggingTracer, showing slow operations for different services. ```json [ { "top":[ { "operation_name":"Get", "server_us":2, "last_local_id":"E64FED2600000001/00000000EA6B514E", "last_local_address":"127.0.0.1:51807", "last_remote_address":"127.0.0.1:11210", "last_dispatch_us":2748, "last_operation_id":"0x9", "total_us":324653 } ], "service":"kv", "count":1 } ] ``` -------------------------------- ### Run the Go Application Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/sample-application.adoc Execute this command in the project's root directory to run the application. The application will be accessible on port 8080. ```console go run . ``` -------------------------------- ### Get and Extend Document Expiry with GetAndTouch Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/kv-operations.adoc The `GetAndTouch` operation retrieves a document and extends its expiry time in a single atomic operation. This is more efficient than separate Get and Touch operations. ```go result, err := collection.GetAndTouch("my_document", 30*time.Minute, gocb.GetAndTouchOptions{}) if err != nil { panic(err) } // Process the document content from result.Content() ``` -------------------------------- ### Perform Get Operation within Transaction Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/distributed-acid-transactions-from-the-sdk.adoc Demonstrates a GET operation within a transaction, ensuring 'Read Your Own Writes' consistency. This operation will succeed even if the document was just modified within the same transaction. ```go err := tx.Get(ctx, "docID", &doc) if err != nil { // Handle error, though ErrDocumentNotFound is often ignorable } ``` -------------------------------- ### Configure Couchbase Connection Environment Variables Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/sample-application.adoc Create a .env file by copying .env.example and populate it with your Couchbase connection details. ```shell CONNECTION_STRING= USERNAME= PASSWORD= ``` -------------------------------- ### Example Orphaned Responses JSON Log Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/observability-orphan-logger.adoc This is a prettified example of the JSON blob that the OrphanReporter logs for observed orphaned responses. Note that the logging output format is not guaranteed to be stable across minor versions. ```json { "kv": { "total_count": 3, "top_requests": [ { "last_local_id": "6fc84f6b1e27f9ec/1264152ff6b5299a", "operation_id": "0x7", "last_remote_socket": "10.112.230.102:11210", "last_local_socket": "10.112.230.1:63747", "last_server_duration_us": 243, "operation_name": "CMD_SET" }, { "last_local_id": "6fc84f6b1e27f9ec/1264152ff6b5299a", "operation_id": "0x8", "last_remote_socket": "10.112.230.102:11210", "last_local_socket": "10.112.230.1:63747", "last_server_duration_us": 300, "operation_name": "CMD_SET" }, { "last_local_id": "6fc84f6b1e27f9ec/1264152ff6b5299a", "operation_id": "0x9", "last_remote_socket": "10.112.230.102:11210", "last_local_socket": "10.112.230.1:63747", "last_server_duration_us": 210, "operation_name": "CMD_SET" } ] } } ``` -------------------------------- ### Get Diagnostics Report Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/health-check.adoc Use Diagnostics to get a list of nodes the SDK currently has connections to and their status. This call does not actively poll nodes, reporting the state from the last access attempt. The report can be marshalled into JSON. ```golang func diagnosticsReport(cluster *couchbase.Cluster) { // ReportID is optional and assigns a name to this report, if empty then a uuid will be assigned. res, err := cluster.Diagnostics(nil) if err != nil { panic(err) } // The report can be marshalled down into JSON in a human friendly format. _ = res } ``` -------------------------------- ### GET Airport Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/sample-application.adoc Fetches a specific airport document. This endpoint expects a GET request with the airport document ID specified in the URL path. The ID is extracted from the URL, and the `GetAirport` method from the `AirportService` is called to retrieve the document. ```APIDOC ## GET Airport ### Description Fetches a specific airport document based on its ID. ### Method GET ### Endpoint `/airport/{id}` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier for the airport document. ### Response #### Success Response (200 OK) - **airportname** (string) - The name of the airport. - **city** (string) - The city where the airport is located. - **country** (string) - The country where the airport is located. - **faa** (string) - The FAA code for the airport. - **icao** (string) - The ICAO code for the airport. - **tz** (string) - The timezone of the airport. - **geo** (object) - Geographic coordinates of the airport. - **lat** (number) - Latitude. - **lon** (number) - Longitude. - **alt** (number) - Altitude. #### Error Response (404 Not Found) - **Error** (string) - Indicates that the document was not found. ``` -------------------------------- ### Getting a User Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/concept-docs/pages/management-api.adoc Retrieves an existing user by their unique identifier. ```APIDOC ## Getting a User ### Description Retrieves an existing user by their unique identifier. ### Method Signature User getUser (String userid) ### Parameters #### Path Parameters - **userid** (String) - Required - The ID of the user to retrieve. ### Response #### Success Response - **User** (Object) - An object containing user details. - **name** (String) - The full name of the user. - **id** (String) - The user's ID. - **domain** (String) - The user's domain (`local` or `external`). - **roles** (Array of Role) - An array of role objects assigned to the user. ``` -------------------------------- ### SDK 3 Connection and Document Fetch Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Illustrates the SDK 3 connection lifecycle, including obtaining a collection and fetching a document. Note that Bucket() and Get() return immediately, with error handling deferred to the operation. ```golang cluster, err := gocb.Connect("127.0.0.1") if err != nil { panic(err) } bucket := cluster.Bucket("travel-sample") // IMPORTANT: Bucket(string) returns immediately, even if the bucket resources are not completely opened. // The SDK will handle this case transparently, and reschedule the operation until the bucket is opened properly. collection := bucket.DefaultCollection() getResult, err := collection.Get("airline_10", nil) if err != nil { // Handle error } ``` -------------------------------- ### Key-Value Operations: Get Source: https://context7.com/couchbase/docs-sdk-go/llms.txt Retrieves a document by its key. The content is deserialized into a provided Go struct. ```APIDOC ## Key-Value Operations: Get `collection.Get()` retrieves a document by its key. The result's content is deserialized via `result.Content(&ptr)`. ### Method `collection.Get(key string, opts *GetOptions) (*GetResult, error)` ### Parameters #### Key - **key** (string) - The unique identifier for the document to retrieve. #### Options - **opts** (`*GetOptions`) - Optional settings for the get operation. - **Timeout** (`time.Duration`) - The maximum time to wait for the operation to complete. ### Returns - **`*GetResult`**: Contains the document's content and metadata. - **Content(dest interface{})**: A method to deserialize the document's content into the provided Go struct (`dest`). - **`error`**: An error if the operation fails, such as `ErrDocumentNotFound`. ### Example ```go getResult, err := col.Get("u:jade", nil) if err != nil { log.Fatal(err) } var user User if err := getResult.Content(&user); err != nil { log.Fatal(err) } fmt.Printf("User: %+v\n", user) // Expected output: User: {Name:Jade Email:jade@test-email.com Interests:[Swimming Rowing]} ``` ``` -------------------------------- ### Create a Bucket Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/provisioning-cluster-resources.adoc Use the BucketManager to create a new bucket with specified settings. Ensure all required parameters like Name and RAMQuotaMB are provided. ```golang settings := gocb.BucketSettings{ Name: "hello", RAMQuotaMB: 100, BucketType: gocb.BucketTypeCouchbase, } err := bucketMgr.CreateBucket(settings) if err != nil { panic(err) } ``` -------------------------------- ### Set Up Logging in Go Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/student-record-developer-tutorial.adoc Configure logging for the Couchbase Go SDK. This file sets up a logger to capture SDK output and errors. ```go package main import ( "log" "os" "github.com/couchbase/gocb/v2" ) func main() { // Connect to Couchbase options := gocb.ClusterOptions{ // TODO: Replace with your connection string and credentials Username: "", Password: "", } cluster, err := gocb.Connect("", options) if err != nil { log.Fatalf("Error connecting to cluster: %v", err) } // Ensure the cluster connection is closed when the application exits defer func() { err := cluster.Close(nil) // Pass a context if needed if err != nil { log.Printf("Error closing cluster: %v", err) } }() // Select the bucket bucket, err := cluster.Bucket("student-record") if err != nil { log.Fatalf("Error selecting bucket: %v", err) } // Wait for the bucket to be ready err = bucket.WaitUntilReady(nil, gocb.WaitUntilReadyOptions{}) if err != nil { log.Fatalf("Error waiting for bucket: %v", err) } // Get a collection object collection := bucket.DefaultCollection() // Log SDK version and collection name agentVersion := cluster.AgentVersion() log.Printf("SDK Version: %s", agentVersion) log.Printf("Using collection: %s/%s/%s", bucket.Name(), collection.ScopeName(), collection.Name()) } ``` -------------------------------- ### Get Bucket Manager Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/provisioning-cluster-resources.adoc Instantiate the BucketManager interface through the Cluster.Buckets() method to perform bucket operations. ```golang bucketMgr := cluster.Buckets() ``` -------------------------------- ### Configure Transaction Query Options Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/distributed-acid-transactions-from-the-sdk.adoc Demonstrates how to provide query options for transactional queries using `TransactionQueryOptions`. This allows customization of scan consistency, parameters, and other query behaviors. ```go rows, err := tx.Query(ctx, "SELECT * FROM `travel-sample` WHERE country = $1", gocb.TransactionQueryOptions{ PositionalParameters: []interface{}{"USA"}, ScanConsistency: gocb.QueryScanConsistency.RequestPlus, }) if err != nil { // Handle error } ``` -------------------------------- ### Get a Document Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/start-using-sdk.adoc Retrieves a document from a collection by its key. This operation will fail if no document with the specified ID is found. ```golang // Get a document res, err := collection.Get("documentKey", nil) if err != nil { panic(err) } var myDoc map[string]interface{} err = res.Content(&myDoc) if err != nil { panic(err) } fmt.Printf("Retrieved document: %v\n", myDoc) ``` -------------------------------- ### Combining Search Service and Vector Queries in Go SDK Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/vector-searching-with-sdk.adoc Demonstrates how to integrate traditional full-text search queries with vector queries in a single request. The combination logic (AND/OR) is configurable. ```go include::devguide:example$go/search.go[tag=vector_fts_query_combination] ``` -------------------------------- ### Initialize Go Module Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/student-record-developer-tutorial.adoc Initialize a new Go module for your project. This command creates a go.mod file to manage dependencies. ```console go mod init student-record ``` -------------------------------- ### Get Document Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/kv-operations.adoc Retrieve a full document from the cluster using its key. This is a fundamental operation for accessing stored data. ```go var resultGet interface{} _, err := collection.Get("my_key", &getOpts) if err != nil { panic(err) } ``` -------------------------------- ### Run Integration Tests - Console Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/sample-application.adoc Executes the project's integration tests using the standard Go testing package. Ensure you are in the project's root directory before running. ```bash cd test go test -v ``` -------------------------------- ### Connect to Couchbase Cloud Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/start-using-sdk.adoc Establishes a connection to Couchbase Cloud using the SDK. Ensure you have your connection string and credentials ready. ```golang var cluster *couchbase.Cluster var err error // Connect to Couchbase Cloud cluster, err = couchbase.Connect(os.Getenv("COUCHBASE_CONN_STR"), couchbase.ClusterOptions{ Username: os.Getenv("COUCHBASE_USERNAME"), Password: os.Getenv("COUCHBASE_PASSWORD"), }) if err != nil { panic(err) } // Select a bucket bucket, err := cluster.Bucket("exampleBucket") if err != nil { panic(err) } // Get a collection collection := bucket.Collection("exampleCollection") // Get a scope scope := bucket.Scope("exampleScope") ``` -------------------------------- ### Update Document with Get and CAS Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/kv-operations.adoc Retrieves a document, modifies it, and updates it using its CAS value to ensure no concurrent modifications. ```go getResp, err := collection.Get("my-document", nil) if err != nil { panic(err) } _, err = collection.Replace("my-document", map[string]interface{}{ "name": "updated example", "value": 456, }, gocb.ReplaceOptions{ Cas: getResp.Cas, }) if err != nil { panic(err) } ``` -------------------------------- ### Create a Development View Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/provisioning-cluster-resources.adoc Use this snippet to create a new design document for development. It specifies the development namespace. ```go err := mgmt.CreateDesignDocument(ctx, "myDesignDoc", "myView", "function(doc){ emit(doc.user, doc.value); }", couchbase.DesignDocumentNamespaceDevelopment) if err != nil { panic(err) } ``` -------------------------------- ### Get Document in Go Transaction Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/distributed-acid-transactions-from-the-sdk.adoc Retrieves a document from a collection within an active transaction. This method returns a TransactionGetResult object. ```go result, err := ctx.Get(collection, documentID) if err != nil { return err } ``` -------------------------------- ### Fetch Key-Value Document (SDK 3) Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Demonstrates fetching a document using the SDK 3 API, returning a Result object. ```golang getResult, err := collection.Get("airline_10", nil) if err != nil { // Handle error } ``` -------------------------------- ### Getting a User Method Signature Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/concept-docs/pages/management-api.adoc Illustrates the method signature for retrieving an existing user by their ID. Returns a User object. ```java User getUser (String userid) ``` -------------------------------- ### Get All Users Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/concept-docs/pages/management-api.adoc Retrieves a list of all users defined in the Couchbase cluster. Each user object contains their name, ID, and domain. ```java List getUsers() ``` -------------------------------- ### Run Go Application Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/student-record-developer-tutorial.adoc Execute your Go application from the terminal to add enrollment details to the student record. ```console go run add_enrollments.go ``` -------------------------------- ### OpenTelemetry Collector Configuration Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/observability-metrics.adoc Example configuration for `opentelemetry-collector` to receive OTLP metrics via gRPC and HTTP, and export them to Prometheus and logging. ```yaml receivers: otlp: protocols: grpc: endpoint: '0.0.0.0:4317' http: endpoint: '0.0.0.0:4318' exporters: logging: loglevel: debug prometheus: endpoint: '0.0.0.0:10000' service: pipelines: metrics: receivers: [otlp] processors: [] exporters: [prometheus, logging] ``` -------------------------------- ### Initialize Services and Controllers Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/sample-application.adoc Initializes the necessary service and controller instances for airlines, airports, and routes, passing the Couchbase scope to the services. ```golang // Initialize the scope scope := db.GetScope(cluster) // Create service instances airlineService := services.NewAirlineService(scope) airportService := services.NewAirportService(scope) routeService := services.NewRouteService(scope) // Create controller instances airlineController := controllers.NewAirlineController(airlineService) airportController := controllers.NewAirportController(airportService) ``` -------------------------------- ### Basic Connection with Username and Password (SDK 3) Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Establishes a connection to the Couchbase cluster using username and password authentication. ```golang cluster, err := gocb.Connect("couchbase://127.0.0.1", gocb.ConnectOptions{ Username: "user", Password: "password", }) if err != nil { panic(err) } ``` -------------------------------- ### Get Document with Timeout Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/kv-operations.adoc Retrieve a full document with a specified timeout. This allows control over how long the SDK will wait for the operation to complete. ```go getOpts := gocb.GetOptions{} getOpts.Timeout = 10 * time.Second var resultGet interface{} _, err := collection.Get("my_key", &getOpts) if err != nil { panic(err) } ``` -------------------------------- ### Configure Transaction Durability Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/distributed-acid-transactions-from-the-sdk.adoc Optionally configure transaction durability globally when creating the Cluster object. This example shows how to set the durability level. ```go import ( "context" "github.com/couchbase/gocb/v2" ) func main() { // Connect to Couchbase opts := gocb.ClusterOptions{ Authenticator: gocb.PasswordAuthenticator{ Username: "Administrator", Password: "password", }, } cluster, err := gocb.Connect(context.Background(), "couchbase://localhost", opts) if err != nil { panic(err) } // Configure transaction durability transactions.Config{DurabilityLevel: gocb.DurabilityLevelMajority}.Apply(cluster) // ... rest of the code } ``` -------------------------------- ### Counter Operations in Go Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/concept-docs/pages/documents.adoc Provides examples for managing counters in Couchbase using the Go SDK. This includes incrementing and decrementing counter values. ```go include::devguide:example$go/documents.go[tag=counters] ``` -------------------------------- ### Connection with Certificate Authenticator (SDK 3) Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Sets up a connection using certificate-based authentication, suitable for enhanced security. ```golang certAuthenticator := gocb.CertificateAuthenticator{ // Certificate and Key paths or data } cluster, err := gocb.Connect("couchbase://127.0.0.1", gocb.ConnectOptions{ Authenticator: certAuthenticator, }) if err != nil { panic(err) } ``` -------------------------------- ### Upsert Document with Enhanced Durability (Go) Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/start-using-sdk.adoc Demonstrates how to upsert a document with enhanced durability settings. Ensure you have the necessary imports and cluster connection established. ```go err = collection.Upsert("my_document_id", document, nil) if err != nil { log.Fatalf("Error upserting document: %v", err) } ``` -------------------------------- ### Connect to Couchbase Capella Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/hello-world/pages/start-using-sdk.adoc Connect to your Couchbase Capella cluster using the provided connection details. The client certificate is included in the SDK installation. ```golang include::devguide:example$go/cloud.go[tag=connect,indent=0] ``` -------------------------------- ### Build Deferred Indexes via Go SDK Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/concept-docs/pages/n1ql-query.adoc Initiates the building process for deferred N1QL indexes using the Go SDK. This command triggers the actual index creation after they have been defined with `defer_build: true`. ```golang func deferredIndex(bucket *couchbase.Bucket) { // Create deferred indexes _, err := bucket.CreateN1QLIndex("idx_city_deferred", []string{"city"}, &couchbase.CreateN1QLIndexOptions{Deferred: true}) if err != nil { panic(err) } // Build the deferred indexes _, err = bucket.BuildN1QLIndex("#primary", "idx_city_deferred") if err != nil { panic(err) } } ``` -------------------------------- ### Get a Document Source: https://context7.com/couchbase/docs-sdk-go/llms.txt Retrieves a document by its key. The document's content is deserialized into the provided pointer. Ensure the key exists before attempting to retrieve. ```go getResult, err := col.Get("u:jade", nil) if err != nil { log.Fatal(err) } var user User if err := getResult.Content(&user); err != nil { log.Fatal(err) } fmt.Printf("User: %+v\n", user) // Expected output: User: {Name:Jade Email:jade@test-email.com Interests:[Swimming Rowing]} ``` -------------------------------- ### Connect to Couchbase Cluster with LDAP Authentication Source: https://github.com/couchbase/docs-sdk-go/blob/release/2.12/modules/howtos/pages/sdk-authentication.adoc Connect to a Couchbase cluster using LDAP for authentication. This example demonstrates connecting with an insecure LDAP connection. ```golang import ( cluster "github.com/couchbase/gocb/v2" ) func main() { // ENDPOINT 1 // Connect to Couchbase cluster with LDAP authentication // Provide connection string with username and password for LDAP opts := cluster.ClusterOptions{ Username: "user", Password: "password", } // Use "couchbase://" for insecure LDAP connections cr, err := cluster.Connect(context.Background(), "couchbase://192.168.1.100", opts) if err != nil { panic(err) } // Select default collection collection := cr.Collection("default") // Get document _, err = collection.Get("docID", nil) if err != nil { panic(err) } // Disconnect cr.Close(context.Background()) } ```