introduzione
Questa guida spiega come creare l' archiviazione di oggetti Vultr nell'applicazione Go con il client Vultr Go . Vultr Object Storage è compatibile con l'API S3.
Prerequisiti
- Un computer con Windows, Linux o macOS con Go 1.12+ installato.
- Conoscenza di base della programmazione.
- Facoltativo: un IDE che supporta Go (ad esempio Visual Studio Code, emacs o Atom).
Creazione di oggetti di archiviazione con il client Vultr Go
Il client Vultr Go viene utilizzato per interagire con l' API Vultr . L'API Vultr ti consente di controllare le risorse associate al tuo account, incluso l'archiviazione degli oggetti Vultr. Informazioni dettagliate sul client Vultr Go sono disponibili in questo articolo .
Crea la cartella del progetto
Crea la cartella nella directory corrente.
$ mkdir vultr_demo
Inserisci la nuova cartella
$ cd vultr_demo
Inizializza il modulo
$ go mod init vultr_demo
Scarica la libreria
$ go get github.com/vultr/govultr
Imposta la variabile di ambiente chiave API
Imposta la variabile di ambiente VULTR_API_KEY sulla tua chiave API. La chiave API è disponibile qui: https://my.vultr.com/settings/#settingsapi
Avviso: proteggi la tua chiave API come se stessi proteggendo la tua password. La chiave API ha accesso all'intero account, inclusi fatturazione, server e spazio di archiviazione.
Ad esempio, su Ubuntu Linux, aggiungi questa riga a ~/.profile
.
export VULTR_API_KEY=YOUR_API_KEY_HERE
Crea il programma Go
Incollare ciascuno dei seguenti frammenti di codice in un nuovo file denominato main.go
. Il file completo è anche disponibile per il download .
Imposta il pacchetto e importa le librerie richieste.
package main
import (
"context"
"log"
"os"
"time"
"github.com/vultr/govultr"
)
Inizia la main()
funzione.
func main() {
Leggi la variabile d'ambiente chiave API.
var (
// Get our Vultr API Key from an environment variable.
VultrAPIKey = os.Getenv("VULTR_API_KEY")
)
Crea il client Vultr.
// Create a Vultr client with our API Key.
vultr := govultr.NewClient(nil, VultrAPIKey)
Specificare un percorso per creare l'archiviazione oggetti. Recupera i percorsi dei cluster, verifica che uno sia disponibile, scegli un cluster e visualizzalo.
// Find the clusters we can create our Object Storage in.
clusters, err := vultr.ObjectStorage.ListCluster(ctx)
if err != nil {
log.Fatalf("Error listing clusters: %s", err)
}
// Verify there's at least one cluster.
if len(clusters) < 1 {
log.Fatal("Could not find any clusters to create our Object Storage")
}
// Choose the first cluster, and print it.
cluster := clusters[0]
log.Printf("Chosen cluster: %+v", cluster)
Creare l'archivio oggetti nel cluster selezionato.
// Create our Object Storage in the first cluster listed with our custom label.
label := "my-object-storage"
storageID, err := vultr.ObjectStorage.Create(ctx, cluster.ObjectStoreClusterID, label)
if err != nil {
log.Fatalf("Error creating storage: %s", err)
}
log.Printf("Created our Object Storage with the ID: %d", storageID.ID)
Attendere fino a quando la memorizzazione degli oggetti è attiva.
var storage govultr.ObjectStorage
// Query the API every five seconds to until our server is ready.
for {
// List all of the Object Storage containers with our label and include the S3 credentials.
list, err := vultr.ObjectStorage.List(ctx, &govultr.ObjectListOptions{
Label: label,
IncludeS3: true,
})
if err != nil {
log.Fatalf("Error listing storage with label \"%s\": %s", label, err)
}
// Make sure we found one (and only one) Object Storage container.
if len(list) != 1 {
log.Fatalf("%d object storage containers exist with the label \"%s\"; we need 1", len(list), label)
}
storage = list[0]
// If the server is active, break out of this loop.
if storage.Status == "active" {
break
}
// Wait for five seconds before querying the API again.
log.Printf("The Object Storage's status is currently \"%s\", waiting for another five seconds to check if it's \"active\".", storage.Status)
time.Sleep(time.Second * 5)
}
Visualizza il nome dell'endpoint e le credenziali di connessione.
// Print the information of our new Object Storage.
log.Print("Successfully created and listed our Object Storage!")
log.Printf("Object Storage: %+v", storage)
// We also have S3 credentials here now, so we could open an S3 compatible client.
log.Printf("S3 credentials: %s - %s - %s", storage.S3Hostname, storage.S3AccessKey, storage.S3SecretKey)
Termina la funzione principale.
// end main()
}
Salvare ed eseguire il main.go
file completato .
go run main.go
Esempio di output
2020/03/03 13:05:48 Chosen cluster: {ObjectStoreClusterID:2 RegionID:1 Location:New Jersey Hostname:ewr1.vultrobjects.com Deploy:yes}
2020/03/03 13:05:48 Created our Object Storage with the ID: xxxxxxxx
2020/03/03 13:05:49 The Object Storage's status is currently pending, waiting for another five seconds to check if it's active.
2020/03/03 13:06:06 Object Storage: {ID:34214512 DateCreated:2020-03-03 13:05:47 ObjectStoreClusterID:2 RegionID:1 Location:New Jersey Label:my-object-storage Status:active S3Keys:{S3Hostname:ewr1.vultrobjects.com S3AccessKey:[REDACTED ACCESS KEY] S3SecretKey:[REDACTED SECRET KEY]}}
2020/03/03 13:06:06 S3 credentials: ewr1.vultrobjects.com - [REDACTED ACCESS KEY] - [REDACTED SECRET KEY]
In questo esempio, il nome dell'endpoint è ewr1.vultrobjects.com e le chiavi vengono redatte. Accedi al tuo nuovo archivio oggetti con qualsiasi client compatibile S3 usando il nome dell'endpoint, la chiave di accesso e la chiave segreta mostrata dal tuo programma Go.