Use Go SDK V2 para establecer y obtener la lista de control de acceso (ACL) de un objeto.
Notas de uso
El código de ejemplo de este tema usa la región China (Hangzhou) (
cn-hangzhou) y el endpoint público. Para acceder a OSS desde otros productos de Alibaba Cloud en la misma región, use un endpoint interno. Para más información sobre las asignaciones entre regiones y endpoints, consulte OSS regions and endpoints.El código de ejemplo lee las credenciales de acceso desde variables de entorno. Para más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.
Para establecer los permisos de acceso de un objeto, debe contar con el permiso
oss:PutObjectAcl. Para obtener los permisos de acceso de un objeto, debe contar con el permisooss:GetObjectAcl. Para más información, consulte Grant a custom policy to a RAM user.
Tipos de ACL
La siguiente tabla describe los cuatro tipos de ACL para objetos.
|
Permiso de acceso |
Descripción |
Valor del permiso de acceso |
|
Heredar del bucket |
El objeto hereda los permisos de acceso del bucket. |
oss.ObjectACLDefault |
|
Privado |
Solo el propietario del objeto y los usuarios autorizados tienen permisos de lectura y escritura sobre el objeto. Los demás usuarios no pueden acceder al objeto. |
oss.ObjectACLPrivate |
|
Lectura pública |
El propietario del objeto y los usuarios autorizados tienen permisos de lectura y escritura sobre el objeto. Los demás usuarios solo tienen permisos de lectura. Tenga precaución al otorgar este permiso. |
ObjectACLPublicRead |
|
Lectura y escritura públicas |
Todos los usuarios tienen permisos de lectura y escritura sobre el objeto. Tenga precaución al otorgar este permiso. |
oss.ObjectACLPublicReadWrite |
La ACL de un objeto tiene prioridad sobre la ACL del bucket. Por ejemplo, si la ACL del bucket es privada pero la ACL del objeto es de lectura y escritura públicas, todos los usuarios tienen permisos de lectura y escritura sobre el objeto. Si no se establece ninguna ACL para un objeto, este hereda la ACL del bucket.
Código de ejemplo
El siguiente código muestra cómo establecer y obtener la ACL de un objeto.
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The region where the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// The init function is used to initialize command-line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command-line parameters.
flag.Parse()
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configurations and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to set the ACL of the object.
putRequest := &oss.PutObjectAclRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
Acl: oss.ObjectACLPrivate, // Set the ACL of the object to private.
}
// Execute the operation to set the ACL of the object.
putResult, err := client.PutObjectAcl(context.TODO(), putRequest)
if err != nil {
log.Fatalf("failed to put object acl %v", err)
}
// Print the result of setting the object ACL.
log.Printf("put object acl result:%#v\n", putResult)
// Create a request to obtain the ACL (access control list) of the object.
getRequest := &oss.GetObjectAclRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
}
// Execute the operation to obtain the ACL of the object.
getResult, err := client.GetObjectAcl(context.TODO(), getRequest)
if err != nil {
log.Fatalf("failed to get object acl %v", err)
}
// Print the result of obtaining the object ACL.
log.Printf("get object acl result:%#v\n", getResult)
}
Referencias
Para ver el código de ejemplo completo usado para establecer la ACL de un objeto, consulte Ejemplo en GitHub.
Para más información sobre la operación de API usada para establecer la ACL de un objeto, consulte PutObjectAcl.
Para ver el código de ejemplo completo usado para obtener la ACL de un objeto, consulte Ejemplo en GitHub.
Para más información sobre la operación de API usada para obtener la ACL de un objeto, consulte GetObjectAcl.