O Object Storage Service (OSS) gera uma URL com base no endpoint público do bucket para cada objeto carregado. Para acessar objetos com um nome de domínio personalizado, adicione um registro CNAME e mapeie o domínio ao bucket.
Observações
O código de exemplo usa o ID da região
cn-hangzhoureferente à região China (Hangzhou). Por padrão, o sistema utiliza o endpoint público. Caso precise acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região do bucket, utilize um endpoint interno. Para mais informações sobre regiões e endpoints compatíveis, consulte Regiões e Endpoints.Os exemplos deste tópico leem credenciais de acesso em variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Go SDK V1).
Código de exemplo
Create a CNAME token
Use o código a seguir para criar um token 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 o código a seguir para obter um token 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
Se o certificado não for mais necessário para o nome de domínio, desassocie-o.
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 o código a seguir para listar os registros CNAME de um 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 o código a seguir para excluir um 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)
}
Referências
Para a operação de API de criação de token CNAME para verificação de propriedade de domínio, consulte CreateCnameToken.
Para a operação de API de obtenção de token CNAME, consulte GetCnameToken.
Para a operação de API de adição de registro CNAME, consulte PutCname.
Para a operação de API de listagem de registros CNAME, consulte ListCname.
Para a operação de API de exclusão de registro CNAME, consulte DeleteCname.