In this article, you will learn how to connect to a Couchbase Capella cluster to create, read, update, and delete documents and how to write simple parametrized SQL++ queries.
Prerequisiti
Per eseguire questo progetto preconfigurato, avrete bisogno di:
-
Couchbase Capella cluster with Travel-sample La carretta è carica.
-
Golang v1.21.x installed
-
Caricamento del contenitore di campioni per il viaggio Se il file travel-sample non è stato caricato nel vostro cluster Capella, potete caricarlo seguendo le istruzioni per il vostro cluster Capella:
Note that this tutorial is designed to work with the latest Golang SDK (2.x) for Couchbase. It will not work with the older Golang SDK for Couchbase without adapting the code.
Configurazione di Couchbase Capella
Quando si esegue Couchbase utilizzando Capella, Per poter utilizzare questo servizio, è necessario soddisfare i seguenti requisiti preliminari.
- L'applicazione richiede che il bucket dei campioni di viaggio sia caricato nel cluster della Capella UI.
- Creare il credenziali del database per accedere al bucket travel-sample (Read e Write) utilizzato nell'applicazione.
- Consenti l'accesso al cluster dal IP su cui è in esecuzione l'applicazione.
Configurazione dell'applicazione
Cloning Repo
git clone https://github.com/couchbase-examples/golang-quickstart.git
Installare le dipendenze
Any dependencies will be installed by running the go run command, which installs any dependencies required from the go.mod file.
Configurazione della database di configurazione
Per saperne di più su come connettersi al cluster Capella, si prega di seguire le istruzioni riportate nella pagina dedicata. istruzioni.
In particolare, è necessario fare quanto segue:
- Creare il credenziali del database per accedere al bucket travel-sample (Read e Write) utilizzato nell'applicazione.
- Consenti l'accesso al cluster dal IP su cui è in esecuzione l'applicazione.
All configuration for communication with the database is read from the environment variables. We have provided a convenience feature in this quickstart to read the environment variables from a local file, .env nella cartella sorgente.
Create a copy of .env.example & rename it to .env & add the values for the Couchbase connection.
CONNECTION_STRING=<connection_string>
USERNAME=<user_with_read_write_permission_to_travel-sample_bucket>
PASSWORD=<password_for_user>
Nota: La stringa di connessione prevede
couchbases://ocouchbase://parte.
Lanciare l'applicazione
Direttamente sulla macchina locale
In questo momento abbiamo installato le dipendenze, caricato i dati del travel-sample e configurato l'applicazione con le credenziali. L'applicazione è ora pronta e potete lanciarla.
L'applicazione verrà eseguita sul port 8080 della macchina locale (http://localhost:8080). Troverete la documentazione Swagger sull'API che potete utilizzare per provare gli endpoint dell'API.
# Execute this command in the project's root directory
go run .
Usare Docker
Se preferite eseguire questa rapida introduzione utilizzando Docker, abbiamo fornito il Dockerfile che potete utilizzare per creare l'immagine e eseguire l'API come container.
- Creare l'immagine Docker
# Execute this command in the project's root directory
docker build -t couchbase-gin-gonic-quickstart .
- Iniziare a eseguire l'immagine Docker
# Execute this command in the project's root directory
docker run -it --env-file .env -p 8080:8080 couchbase-gin-gonic-quickstart
Nota: Il
.envIl file contiene le informazioni di connessione per connettersi al cluster Capella. Con il--env-file, docker will inject those environment variables to the container. The application is now running and you can launch your browser and go to the Swagger documentation per testare le API.
Once the app is up and running, you can launch your browser and go to the Swagger documentation per testare le API.
Verificare l'applicazione
Una volta avviata l'applicazione, è possibile visualizzare i dettagli dell'applicazione nei log.

L'applicazione verrà eseguita sul port 8080 della macchina locale (http://localhost:8080). Potrete trovare la documentazione interattiva di Swagger per l'API accedendo all'URL nel vostro browser. La documentazione di Swagger viene utilizzata in questa demo per illustrare i diversi punti di accesso all'API e come essi possono essere chiamati. Ulteriori dettagli sulla documentazione di Swagger sono disponibili nella sezione appendice.

Modello dei dati
Per questo tutorial utilizzeremo tre collezioni:, aeroporto, aerolinea e itinerario che contengono rispettivamente aeroporti campione, compagnie aeree e rotte aeree. La raccolta di rotte collega gli aeroporti e le compagnie aeree come mostrato nella figura sottostante. Usiamo queste connessioni nel quickstart per generare aeroporti direttamente collegati e compagnie aeree che collegano un aeroporto di destinazione. Nota che questi sono solo esempi per evidenziare come è possibile utilizzare le query SQL++ per aggregare le collezioni.

Proviamo a rivedere il codice
Per iniziare questo tutorial, clonate il repo e apriamolo nell'IDE di vostra scelta. Ora potete imparare come creare, leggere, aggiornare e cancellare documenti in Couchbase Server.
Layout del codice
├── controllers
│ ├── airline_controller.go
│ ├── airport_controller.go
│ └── route_controller.go
├── db
│ ├── db.go
├── errors
│ ├── errors.go
├── models
│ ├── collection_models.go
├── routes
│ ├── route.go
├── service
│ ├── airline.go
│ ├── airport.go
│ └── route.go
├── go.mod
├── main.go
├── Dockerfile
└── test
├── airline_test.go
├── airport_test.go
├── main_test.go
└── route_test.go
We have separated out the code into separate files by the entity (collection) in the controllers e service la cartella. I test sono inoltre suddivisi per entità nella testi cartella.
In main.go a couchbase cluster is initialized using the InitializeCluster function from the db package.
# main.go
// Initialize the cluster
cluster := db.InitializeCluster()
La connessione a Couchbase viene stabilita nel InitializeCluster function defined in db.go. Lì, chiamiamo il Connettersi method defined in the SDK to create the Database connection. In our application, we have the same bucket(travel-sample) and scope that is used by all the APIs. We initialise this scope and return it in the GetScope function. The collection will change depending on the API route.
# db.go
// Configure cluster options
clusterOpts := gocb.ClusterOptions{
Authenticator: gocb.PasswordAuthenticator{
Username: username,
Password: password,
},
}
// Sets a pre-configured profile called "wan-development" to help avoid latency issues
if err := clusterOpts.ApplyProfile(gocb.ClusterConfigProfileWanDevelopment); err != nil {
panic(err)
}
// Connect to the Couchbase cluster
cluster, err := gocb.Connect(connectionString, clusterOpts)
if err != nil {
panic(err)
}
In main.go we then fetch the scope from the GetScope function defined in the db.go by passing the cluster initialised.
We then initialise the service and controller for all the collections.
The instances of the collections are then passed to the SetupCollectionRoutes function from the routes package. This function sets up the HTTP routes and their corresponding handlers.
// 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)
routeController := controllers.NewRouteController(routeService)
// Pass to Controllers struct to hold controller instances
controllers := routes.Controllers{
AirlineController: airlineController,
AirportController: airportController,
RouteController: routeController,
}
// Setup routes and pass the Controllers struct
routes.SetupCollectionRoutes(router, controllers)
Entità aeroportuale
For this tutorial, we will focus on the airport entity. The other entities are similar.
Stabiliremo un'API REST per gestire i documenti aeroportuali.
- Aeroporto POST – Creare un nuovo aeroporto
- GET Airport – Leggere l'aeroporto specificato
- Aeroporto di PUT – Aggiornamento aeroporto specificato
- DELETE Airport – Eliminare l'aeroporto
- Elenco degli aeroporti – Raccogliere tutti gli aeroporti. Opzionalmente è possibile filtrare l’elenco per paese
- Connessioni dirette – Ottieni una lista di aeroporti direttamente collegati all'aeroporto specificato
Per le operazioni CRUD utilizzeremo il Operazioni chiave-valore che sono integrate nel Couchbase SDK per creare, leggere, aggiornare e cancellare un documento. Ogni documento avrà bisogno di un ID (simile a una chiave primaria in altre database) per essere salvato nel database. Questo ID viene passato nell'URL. Per gli altri endpoint, utilizzeremo SQL++ per richiedere documenti.
Struttura dei documenti dell'aeroporto
Il nostro documento di profilo conterrà il nome dell'aeroporto, la città, il paese, il codice FAA, il codice ICAO, le informazioni sulla zona oraria e le coordinate geografiche. Per questa demo, memorizzeremo tutte le informazioni sull'aeroporto in un unico documento nel aeroporto raccolta nel Travel-sample bucket.
{
"airportname": "Sample Airport",
"city": "Sample City",
"country": "United Kingdom",
"faa": "SAA",
"icao": "SAAA",
"tz": "Europe/Paris",
"geo": {
"lat": 48.864716,
"lon": 2.349014,
"alt": 92
}
}
Aeroporto POST
To insert a new airport document, locate the InsertDocumentForAirport method within the airport_controller file found in the controllers package. This expects a POST request with the airport ID (id) specified in the URL path and the airport data provided in the request body.
We extract this airport ID from the URL, parse the request data, and call the CreateAirport method from the AirportService.
// InsertDocumentForAirport method in controllers/airline_controller.go
docKey := context.Param("id")
data := models.Airport{}
if err := context.ShouldBindJSON(&data); err != nil {
context.JSON(http.StatusBadRequest, cError.Errors{
Error: "Error, Invalid request data: " + err.Error(),
})
return
}
err := ac.AirportService.CreateAirport(docKey, &data)
context.JSON(http.StatusCreated, data)
The CreateAirport method calls the Insert method for the collection defined in the Couchbase SDK. The insert method takes the key (id) by which the document is referenced and the content to be inserted into the collection.
// CreateAirport in service/airport.go
func (s *AirportService) CreateAirport(docKey string, data *models.Airport) error {
_, err := s.scope.Collection(s.collectionName).Insert(docKey, data, nil)
if err != nil {
return err
}
return nil
}
If the document id already exists in the database, we get an error, ErrDocumentExists from the SDK and return the status as 409.
GET Airport
To fetch a airport document, locate the GetDocumentForAirport method within the airport_controller file found in the controllers package. This expects a GET request with the airport document ID (id) specified in the URL path.
We extract this airport document ID from the URL and call the GetAirport method from the AirportService.
// GetDocumentForAirport in controllers/airport_controller.go
docKey := context.Param("id")
airportData, err := ac.AirportService.GetAirport(docKey)
Il GetAirport method chiama il Get method defined for collections in the Couchbase SDK. We fetch the document based on the key by which it is stored. If the document retrieval was successful, it decodes the content of the document into a models.Airport struct using the Content method.
// GetAirport in service/airport.go
func (s *AirportService) GetAirport(docKey string) (*models.Airport, error) {
getResult, err := s.scope.Collection(s.collectionName).Get(docKey, nil)
if err != nil {
return nil, err
}
var airportData models.Airport
if err := getResult.Content(&airportData); err != nil {
return nil, err
}
return &airportData, nil
}
If the document is not found in the database, we get an error, ErrDocumentNotFound da SDK e restituisci lo stato come 404.
Aeroporto di PUT
To update a airport document, locate the UpdateDocumentForAirport method within the airport_controller file found in the controllers package.
This expects a PUT request with the airport ID (id) specified in the URL path and the airport data to be updated provided in the request body.
We extract this airport ID(id) from the URL, parse the request data, and call the UpdateAirport method from the AirportService.
// UpdateDocumentForAirport in controllers/airport_controller.go
docKey := context.Param("id")
data := models.Airport{}
if err := context.ShouldBindJSON(&data); err != nil {
context.JSON(http.StatusBadRequest, cError.Errors{
Error: "Error while getting the request: " + err.Error(),
})
return
}
err := ac.AirportService.UpdateAirport(docKey, &data)
Il UpdateAirport method chiama il Upsert method for the collection defined in the Couchbase SDK. The upsert method takes the key (id) by which the document is referenced and the content to be updated into the collection.
// UpdateAirport in service/airport.go
func (s *AirportService) UpdateAirport(docKey string, data *models.Airport) error {
_, err := s.scope.Collection(s.collectionName).Upsert(docKey, data, nil)
if err != nil {
return err
}
return nil
}
DELETE Airport
To delete a airport document, locate the DeleteDocumentForAirport method within the airport_controller file found in the controllers package.
This expects a DELETE request with the airport document ID (id) specified in the URL path.
We extract this airport document ID from the URL and call the DeleteAirport method from the AirportService.
// DeleteDocumentForAirport in controllers/airport_controller.go
docKey := context.Param("id")
err := ac.AirportService.DeleteAirport(docKey)
Il DeleteAirport method chiama il Remove method defined for collections in the Couchbase SDK. We delete the document based on the key by which it is stored.
// DeleteAirport in service/airport.go
func (s *AirportService) DeleteAirport(docKey string) error {
_, err := s.scope.Collection(s.collectionName).Remove(docKey, nil)
if err != nil {
return err
}
return nil
}
If the document is not found in the database, we get an error, ErrDocumentNotFound da SDK e restituisci lo stato come 404.
Lista aeroporti
Questo endpoint recupera l'elenco degli aeroporti presenti nel database. L'API offre la possibilità di specificare la dimensione della pagina dei risultati e il paese da cui estrarre i documenti relativi agli aeroporti.
SQL++ is a powerful query language based on SQL, but designed for structured and flexible JSON documents. We will use a SQL+ query to search for airports with Limit, Offset, and Country option.
Navigare fino alla GetAirports il metodo nel airport_controller file found in the controllers package. This endpoint is different from the others we have seen before because it makes the SQL++ query rather than a key-value operation. This usually means more overhead because the query engine is involved. For this query, we are using the predefined indices in the Travel-sample bucket. Possiamo creare un altro indice specifico per questa query per renderla più efficiente.
First, we need to get the values from the query string for country, limit, and Offset that we will use in our query. These are pulled from the context.DefaultQuery method for country and limit,offset respectively.
Questo endpoint ha due query a seconda del valore del parametro Paese. Se viene specificato un nome di paese, recuperiamo i documenti relativi all’aeroporto per quel paese specifico. Se non viene specificato, recuperiamo l’elenco degli aeroporti di tutti i paesi. Le query sono leggermente diverse per questi due scenari.
Costruiamo la nostra query SQL++ utilizzando il named parameters specificato da $ symbol for both these scenarios. A named or positional parameter is a placeholder for a value in the WHERE, LIMIT or OFFSET clause of a query. The difference between the two queries is the presence of the paese Il parametro nella query. Normalmente, per le query con la funzione di paginaazione, si consiglia di ordinare i risultati per mantenere l'ordine dei risultati in più query.
// GetAirports in controllers/airport_controller.go
country := context.DefaultQuery("country", "")
limit, err := strconv.Atoi(context.DefaultQuery("limit", "10"))
if err != nil {
limit = 10
}
offset, err := strconv.Atoi(context.DefaultQuery("offset", "0"))
if err != nil {
offset = 0
}
// Construct the query with named params
if country != "" {
query = `
SELECT airport.airportname,
airport.city,
airport.country,
airport.faa,
airport.geo,
airport.icao,
airport.tz
FROM airport AS airport
WHERE airport.country=$country
ORDER BY airport.airportname
LIMIT $limit
OFFSET $offset;
`
params = map[string]interface{}{
"country": country,
"limit": limit,
"offset": offset,
}
} else {
query = `
SELECT airport.airportname,
airport.city,
airport.country,
airport.faa,
airport.geo,
airport.icao,
airport.tz
FROM airport AS airport
ORDER BY airport.airportname
LIMIT $limit
OFFSET $offset;
`
params = map[string]interface{}{
"limit": limit,
"offset": offset,
}
}
// Use the method to execute the query and return the results
queryResult, err := ac.AirportService.QueryAirport(query, params)
Il QueryAirport method chiama il Interrogazione metodo definito nel Ambito di applicazione by the Couchbase SDK. If the query is executed successfully, it iterates over the result set using queryResult.Next() and deserializes the data. The method returns a slice of models.Airport containing the result documents obtained from the query.
// QueryAirport in service/airport.go
func (s *AirportService) QueryAirport(query string, params map[string]interface{}) ([]models.Airport, error) {
queryResult, err := s.scope.Query(query, &gocb.QueryOptions{NamedParameters: params})
if err != nil {
return nil, err
}
var document models.Airport
var documents []models.Airport
if queryResult == nil {
return nil, err
}
for queryResult.Next() {
err := queryResult.Row(&document)
if err != nil {
return nil, err
}
documents = append(documents, document)
}
return documents, nil
}
Connessioni dirette
This endpoint fetches the airports that can be reached directly from the specified source airport code. This also uses a SQL++ query to fetch the results simlar to the List Airport endpoint. The method returns a slice of models.Destination containing the result documents obtained from the query.
Consideriamo la query utilizzata qui:
query := `
SELECT DISTINCT route.destinationairport
FROM airport AS airport
JOIN route AS route ON route.sourceairport = airport.faa
WHERE airport.faa = $airport AND route.stops = 0
ORDER BY route.destinationairport
LIMIT $limit
OFFSET $offset
`
params := map[string]interface{}{
"airport": airport,
"limit": limit,
"offset": offset,
}
// Use the method to execute the query and return the results
queryResult, err := ac.AirportService.QueryDirectConnectionAirport(query, params)
Il QueryDirectConnectionAirport method returns a slice of models.Destination containing the result documents obtained from the query.
Raccogliamo le connessioni dirette unendo la raccolta dell'aeroporto alla raccolta del percorso e filtrando in base all'aeroporto di origine specificato dall'utente e alle rotte senza fermate.
Esecuzione dei test
We have defined integration tests using the standard go testing package for all the API end points. The integration tests use the same database configuration as the application. For the tests, we perform the operation using the API and confirm the results by checking the documents in the database. For example, to check the creation of the document by the API, we would call the API to create the document and then read the same document from the database and compare them. After the tests, the documents are cleaned up by calling the DELETE endpoint.
# Run standard tests for the project
cd test
go test -v
Appendice
Ampliare l'API aggiungendo un'entità nuova
Se desiderate aggiungere un'altra entità alle API, i passaggi da seguire sono i seguenti:
-
Create the New Entity in Couchbase Bucket:
- Utilize the SDK or the Interfaccia del server Couchbase to establish the new collection within the Couchbase bucket.
-
Define the New Route:
- Navigare fino alla
route/routes.gofolder and create the new route.
- Navigare fino alla
-
Controller Configuration:
- Develop a new file in the
controllersfolder, mirroring the existing structures (e.g.,airport_controller.go). Craft the corresponding method within this file to manage the new entity.
- Develop a new file in the
-
Service Layer Implementation:
- Generate a new file in the
servicefolder, modeling it after the existing service files (e.g.,airport.go). Construct the service logic pertinent to the operations involving the new entity.
- Generate a new file in the
-
Add Tests:
- Aggiungere i test per le nuove rotte in un nuovo file nel
testuna cartella simile aairport_test.go.
- Aggiungere i test per le nuove rotte in un nuovo file nel
Following these steps ensures a systematic and organized approach to expanding the API functionality with a new entity.
Gestione automatica di un cluster di Couchbase
Se stai eseguendo questo quickstart con un cluster di Couchbase gestito autonomamente, è necessario caricare caricare i dati del bucket dei dati di viaggio nel cluster e generare le credenziali per il bucket.
- Seguimi Opzioni di installazione di Couchbase Per l'installazione dell'ultima istanza del server di database Couchbase.
È necessario aggiornare la stringa di connessione e le credenziali nel file .env file nella cartella di origine.
Note: Couchbase Server must be installed and running prior to running the app.
Documentazione Swagger
La documentazione di Swagger fornisce una panoramica chiara dell'API, includendo endpoint, metodi HTTP, parametri delle richieste e oggetti di risposta.
Fare clic su un singolo endpoint per ampliarlo e visualizzare le informazioni dettagliate. Ciò include la descrizione dell’endpoint, i possibili codici di stato delle risposte e i parametri della richiesta che esso accetta.
Testare l'API
È possibile provare un'API cliccando sul pulsante “Prova” accanto agli endpoint.
-
Parametri: Se un endpoint richiede parametri, l'interfaccia utente Swagger fornisce dei campi di input da compilare. Questi possono includere parametri di percorso, stringhe di query, intestazioni o il corpo di una richiesta POST/PUT.
-
Esecuzione: Una volta inseriti tutti i parametri necessari, è possibile cliccare sul pulsante “Esecuzione” per effettuare una chiamata API in tempo reale. L’interfaccia utente Swagger invierà la richiesta all’API e visualizzerà la risposta direttamente nella documentazione. Ciò include il codice della risposta, gli header e il corpo della risposta.
Modelli
Swagger documenta la struttura dei corpi di richiesta e risposta utilizzando modelli. Questi modelli definiscono la struttura dei dati prevista utilizzando lo schema JSON e sono estremamente utili per comprendere quali dati inviare e quali aspettarsi.