All Products
Search
Document Center

:Map custom domain names using OSS SDK for Go

Last Updated:Feb 27, 2025

After you upload objects to a bucket, Object Storage Service (OSS) automatically generates URLs that include the public endpoint of the bucket for the uploaded objects. You can use these URLs to access the objects. If you want to access the objects by using a custom domain name, you must add a CNAME record to map the custom domain name to the bucket in which the objects are stored.

Notes

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about the regions and endpoints supported by Object Storage Service (OSS), see OSS regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

Sample code

Create a CNAME token

The following code provides an example of how to create a CNAME token.

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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential 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{
			Domain: oss.Ptr("www.example.com"), // Specify the custom domain name.
		},
	}

	// Perform the operation to create a CNAME token.
	result, err := client.CreateCnameToken(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to create bucket cname token %v", err)
	}

	// Display information about the CNAME token.
	log.Printf("Cname: %s", *result.CnameToken.Cname)
	log.Printf("Token: %s", *result.CnameToken.Token)
	log.Printf("ExpireTime: %s", *result.CnameToken.ExpireTime)
}

Query a CNAME token

The following code provides an example of how to query a CNAME token.

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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify 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 query the CNAME token mapped to the bucket.
	request := &oss.GetCnameTokenRequest{
		Bucket: oss.Ptr(bucketName),        // Name of the bucket.
		Cname:  oss.Ptr("www.example.com"), // Specify the custom domain name.
	}

	// Perform the query operation.
	result, err := client.GetCnameToken(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket cname token %v", err)
	}

	// Display information about the CNAME token.
	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 a 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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify 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 add a CNAME record.
	request := &oss.PutCnameRequest{
		Bucket: oss.Ptr(bucketName),
		BucketCnameConfiguration: &oss.BucketCnameConfiguration{
			Domain: oss.Ptr("www.example.com"), // Specify the custom domain name.
		},
	}

	// Execute the request.
	result, err := client.PutCname(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket cname %v", err)
	}

	// Display the result.
	log.Printf("put bucket cname result:%#v\n", result)
}

Map a custom domain name and associate a certificate with the 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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify 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 map a custom domain name and associate a certificate with the domain name.
	request := &oss.PutCnameRequest{
		Bucket: oss.Ptr(bucketName),
		BucketCnameConfiguration: &oss.BucketCnameConfiguration{
			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)
	}

	// Display the result.
	log.Printf("put bucket cname result:%#v\n", result)
}

Disassociate a certificate

If you do not want the domain name to continue using the certificate, you can disassociate the 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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify 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 disassociate the certificate.
	request := &oss.PutCnameRequest{
		Bucket: oss.Ptr(bucketName),
		BucketCnameConfiguration: &oss.BucketCnameConfiguration{
			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)
	}

	// Display the result.
	log.Printf("put bucket cname result:%#v\n", result)
}

List CNAME records

The following code provides an example of how to list the CNAME records mapped to a 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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify 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 list the CNAME records mapped to 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 {
			// Display the custom domain name.
			log.Printf("Domain: %s", cnameInfo.Domain)
			// Display the point in time when the custom domain name is mapped to the bucket.
			log.Printf("LastModified: %s", cnameInfo.LastModified)
			// Display the status of the domain name.
			log.Printf("Status: %s", cnameInfo.Status)
		}
	}
}

Delete a CNAME record

The following code provides an example of how to delete a CNAME record.

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 // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify 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 delete a CNAME record mapped to the bucket.
	request := &oss.DeleteCnameRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		BucketCnameConfiguration: &oss.BucketCnameConfiguration{
			Domain: oss.Ptr("www.example.com"), // Specify the custom domain name.
		},
	}

	// Execute the operation to delete the CNAME record.
	result, err := client.DeleteCname(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket cname %v", err)
	}

	// Display the result.
	log.Printf("delete bucket cname result:%#v\n", result)
}

References

  • For more information about the API operation that you can call to create a CNAME token to verify the ownership of a domain name, see CreateCnameToken.

  • For more information about the API operation that you can call to query a CNAME token, see GetCnameToken.

  • For more information about the API operation that you can call to add a CNAME record to a bucket, see PutCname.

  • For more information about the API operation that you can call to query the CNAME record mapped to a bucket, see ListCname.

  • For more information about the API operation that you can call to delete a CNAME record mapped to a bucket, see DeleteCname.