Introducción
Esta guía explica cómo crear Vultr Object Storage en su aplicación Go con el cliente Vultr Go . Vultr Object Storage es compatible con la API S3.
Prerrequisitos
- Una computadora con Windows, Linux o macOS con Go 1.12+ instalado.
- Conocimientos básicos de programación.
- Opcional: un IDE que admite Go (por ejemplo, Visual Studio Code, emacs o Atom).
Crear almacenamiento de objetos con el cliente Vultr Go
El cliente Vultr Go se usa para interactuar con la API de Vultr . La API de Vultr le permite controlar los recursos asociados con su cuenta, incluido Vultr Object Storage. La información detallada sobre el cliente Vultr Go está disponible en este artículo .
Crear la carpeta del proyecto
Crea la carpeta en el directorio actual.
$ mkdir vultr_demo
Ingrese la nueva carpeta.
$ cd vultr_demo
Inicializa el módulo
$ go mod init vultr_demo
Descargar la biblioteca
$ go get github.com/vultr/govultr
Establecer la variable de entorno clave API
Establezca la variable de entorno VULTR_API_KEY en su clave API. Su clave API se encuentra aquí: https://my.vultr.com/settings/#settingsapi
Advertencia: Proteja su clave API como protegería su contraseña. La clave API tiene acceso a toda su cuenta, incluida la facturación, los servidores y el almacenamiento.
Por ejemplo, en Ubuntu Linux, agregue esta línea a ~/.profile.
export VULTR_API_KEY=YOUR_API_KEY_HERE
Crea el programa Go
Pegue cada uno de los siguientes fragmentos de código en un nuevo archivo llamado main.go. El archivo completo también está disponible para descargar .
Configure el paquete e importe las bibliotecas necesarias.
package main
import (
"context"
"log"
"os"
"time"
"github.com/vultr/govultr"
)
Comience la main()función.
func main() {
Lea la variable de entorno de la clave API.
var (
// Get our Vultr API Key from an environment variable.
VultrAPIKey = os.Getenv("VULTR_API_KEY")
)
Crea el cliente Vultr.
// Create a Vultr client with our API Key.
vultr := govultr.NewClient(nil, VultrAPIKey)
Especifique una ubicación para crear almacenamiento de objetos. Recupere las ubicaciones del clúster, verifique que haya uno disponible, elija un clúster y muéstrelo.
// 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)
Cree el almacenamiento de objetos en el clúster seleccionado.
// 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)
Espere hasta que el Almacenamiento de objetos esté activo.
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)
}
Muestra el nombre del punto final y las credenciales de conexión.
// 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)
Fin de la función principal.
// end main()
}
Guarde y ejecute el main.goarchivo completado .
go run main.go
Salida de ejemplo
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]
En este ejemplo, el nombre del punto final es ewr1.vultrobjects.com, y las claves se eliminan. Acceda a su nuevo almacenamiento de objetos con cualquier cliente compatible con S3 utilizando el nombre del punto final, la clave de acceso y la clave secreta que muestra su programa Go.