Object Storage Service (OSS) genera una URL basada en el endpoint público del bucket para cada objeto cargado. Para acceder a los objetos mediante un nombre de dominio personalizado, agregue un registro CNAME que asigne el nombre de dominio al bucket.
Notas
El código de ejemplo usa el ID de región
cn-hangzhoucorrespondiente a la región China (Hangzhou). De forma predeterminada, se usa el endpoint público. Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que su bucket, use un endpoint interno. Para obtener más información sobre las regiones y endpoints compatibles, consulte Regions and Endpoints.Los ejemplos de este tema leen las credenciales de acceso desde variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials (Go SDK V1).
Código de ejemplo
Create a CNAME token
Use el siguiente código para crear un token de CNAME.
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.
)
// The init function is used to initialize command-line flags.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse the command-line flags.
flag.Parse()
// Check if the bucket name is provided.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is provided.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configuration, and set the credentials provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a CNAME token.
request := &oss.CreateCnameTokenRequest{
Bucket: oss.Ptr(bucketName),
BucketCnameConfiguration: &oss.BucketCnameConfiguration{
Cname: &oss.Cname{
Domain: oss.Ptr("www.example.com"), // Specify the custom domain name.
},
},
}
// Execute the request to create the CNAME token.
result, err := client.CreateCnameToken(context.TODO(), request)
if err != nil {
log.Fatalf("failed to create bucket cname token %v", err)
}
// Print the CNAME token information.
log.Printf("Cname: %s", *result.CnameToken.Cname)
log.Printf("Token: %s", *result.CnameToken.Token)
log.Printf("ExpireTime: %s", *result.CnameToken.ExpireTime)
}
Get a CNAME token
Use el siguiente código para obtener un token de CNAME.
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.
)
// The init function is used to initialize command-line flags.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse the command-line flags.
flag.Parse()
// Check if the bucket name is provided.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is provided.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configuration, and set the credentials provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to get the CNAME token for the bucket.
request := &oss.GetCnameTokenRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Cname: oss.Ptr("www.example.com"), // Specify the custom domain name.
}
// Execute the request to get the CNAME token.
result, err := client.GetCnameToken(context.TODO(), request)
if err != nil {
log.Fatalf("failed to get bucket cname token %v", err)
}
// Print the CNAME token information.
log.Printf("Cname: %s", result.CnameToken.Cname)
log.Printf("Token: %s", result.CnameToken.Token)
log.Printf("ExpireTime: %s", result.CnameToken.ExpireTime)
}
Add a CNAME record
Map custom domain name
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.
)
// The init function is used to initialize command-line flags.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse the command-line flags.
flag.Parse()
// Check if the bucket name is provided.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is provided.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configuration, and set the credentials provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to add a CNAME record for the bucket.
request := &oss.PutCnameRequest{
Bucket: oss.Ptr(bucketName),
BucketCnameConfiguration: &oss.BucketCnameConfiguration{
Cname: &oss.Cname{
Domain: oss.Ptr("www.example.com"), // Specify the custom domain name.
},
},
}
// Execute the request to add the CNAME record.
result, err := client.PutCname(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put bucket cname %v", err)
}
// Print the result.
log.Printf("put bucket cname result:%#v\n", result)
}
Map domain and certificate
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.
)
// The init function is used to initialize command-line flags.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse the command-line flags.
flag.Parse()
// Check if the bucket name is provided.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is provided.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configuration, and set the credentials provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to map a custom domain name and associate a certificate.
request := &oss.PutCnameRequest{
Bucket: oss.Ptr(bucketName),
BucketCnameConfiguration: &oss.BucketCnameConfiguration{
Cname: &oss.Cname{
Domain: oss.Ptr("www.example.com"), // Specify the custom domain name.
CertificateConfiguration: &oss.CertificateConfiguration{
CertId: oss.Ptr("92******-cn-hangzhou"),
Certificate: oss.Ptr("-----BEGIN CERTIFICATE-----MIIFBzCCA++gT2H2hT6Wb3nwxjpLIfXmSVcV*****-----END CERT"),
PrivateKey: oss.Ptr("-----BEGIN CERTIFICATE-----MIIFBzCCA++gT2H2hT6Wb3nwxjpLIfXmSVcV*****-----END CERTIFICATE-----"),
Force: oss.Ptr(true),
},
},
},
}
// Execute the request.
result, err := client.PutCname(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put bucket cname %v", err)
}
// Print the result.
log.Printf("put bucket cname result:%#v\n", result)
}
Disassociate a certificate
Si el certificado ya no es necesario para el nombre de dominio, desvincúlelo.
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.
)
// The init function is used to initialize command-line flags.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse the command-line flags.
flag.Parse()
// Check if the bucket name is provided.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is provided.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configuration, and set the credentials provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to disassociate the certificate.
request := &oss.PutCnameRequest{
Bucket: oss.Ptr(bucketName),
BucketCnameConfiguration: &oss.BucketCnameConfiguration{
Cname: &oss.Cname{
Domain: oss.Ptr("www.example.com"), // Specify the custom domain name.
CertificateConfiguration: &oss.CertificateConfiguration{
DeleteCertificate: oss.Ptr(true), // Disassociate the certificate.
},
},
},
}
// Execute the request to disassociate the certificate.
result, err := client.PutCname(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put bucket cname %v", err)
}
// Print the result.
log.Printf("put bucket cname result:%#v\n", result)
}
List CNAME records
Use el siguiente código para listar los registros CNAME de un bucket.
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.
)
// The init function is used to initialize command-line flags.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse the command-line flags.
flag.Parse()
// Check if the bucket name is provided.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is provided.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configuration, and set the credentials provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to list the CNAME records for the bucket.
request := &oss.ListCnameRequest{
Bucket: oss.Ptr(bucketName),
}
// Execute the request to list the CNAME records.
result, err := client.ListCname(context.TODO(), request)
if err != nil {
log.Fatalf("failed to list bucket cname %v", err)
}
log.Printf("Bucket: %s", result.Bucket)
log.Printf("Owner: %s", result.Owner)
if len(result.Cnames) > 0 {
for _, cnameInfo := range result.Cnames {
// Print the custom domain name.
log.Printf("Domain: %s", cnameInfo.Domain)
// Print the last modified time.
log.Printf("LastModified: %s", cnameInfo.LastModified)
// Print the status of the domain name.
log.Printf("Status: %s", cnameInfo.Status)
}
}
}
Delete a CNAME record
Use el siguiente código para eliminar un registro CNAME.
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.
)
// The init function is used to initialize command-line flags.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse the command-line flags.
flag.Parse()
// Check if the bucket name is provided.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is provided.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configuration, and set the credentials provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to delete a CNAME record for the bucket.
request := &oss.DeleteCnameRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
BucketCnameConfiguration: &oss.BucketCnameConfiguration{
Cname: &oss.Cname{
Domain: oss.Ptr("www.example.com"), // Specify the custom domain name.
},
},
}
// Execute the request to delete the CNAME record.
result, err := client.DeleteCname(context.TODO(), request)
if err != nil {
log.Fatalf("failed to delete bucket cname %v", err)
}
// Print the result.
log.Printf("delete bucket cname result:%#v\n", result)
}
Referencias
Para consultar la operación de API que crea un token de CNAME para la verificación de propiedad del dominio, consulte CreateCnameToken.
Para consultar la operación de API que obtiene un token de CNAME, consulte GetCnameToken.
Para consultar la operación de API que agrega un registro CNAME, consulte PutCname.
Para consultar la operación de API que lista los registros CNAME, consulte ListCname.
Para consultar la operación de API que elimina un registro CNAME, consulte DeleteCname.