All Products
Search
Document Center

Object Storage Service:Map custom domain names by using OSS SDK for Go

Last Updated:Nov 04, 2024

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.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions, endpoints and open ports.

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

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

Examples

Create a CNAME token

The following sample code provides an example on how to create a CNAME token:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.  
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"
	// Specify the custom domain name. 
	cname := "www.example.com"

	// Create a CNAME token.
	cbResult, err := client.CreateBucketCnameToken(bucketName, cname)
	if err != nil {
		log.Fatalf("Failed to create CNAME token: %v", err)
	}

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

Query a CNAME token

The following sample code provides an example on how to query a CNAME token:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.  
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"
	// Specify the custom domain name. 
	cname := "www.example.com"

	// Query the CNAME token.
	cbResult, err := client.GetBucketCnameToken(bucketName, cname)
	if err != nil {
		log.Fatalf("Failed to get CNAME token: %v", err)
	}

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

Add a CNAME record

Map a custom domain name

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.  
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"
	// Specify the custom domain name. 
	cname := "www.example.com"

	// Map the custom domain name to the bucket.
	err = client.PutBucketCname(bucketName, cname)
	if err != nil {
		log.Fatalf("Failed to put bucket CNAME: %v", err)
	}

	// Display the result.
	log.Println("Put Bucket Cname Success!")
}

Map a custom domain name and associate a certificate with the domain name

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.  
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"

	// Add a CNAME record and configure a certificate.
	putCnameConfig := oss.PutBucketCname{
		Cname: "www.example.com",
		CertificateConfiguration: &oss.CertificateConfiguration{
			CertId:      "92******-cn-hangzhou",
			Certificate: "-----BEGIN CERTIFICATE-----MIIGeDCCBOCgAwIBAgIRAPj4FWpW5XN6kwgU7*******-----END CERTIFICATE-----",
			PrivateKey:  "-----BEGIN CERTIFICATE-----MIIFBzCCA++gT2H2hT6Wb3nwxjpLIfXmSVcV*****-----END CERTIFICATE-----",
			Force:       true,
		},
	}

	// Map a custom domain name and associate a certificate with the domain name.
	err = client.PutBucketCnameWithCertificate(bucketName, putCnameConfig)
	if err != nil {
		log.Fatalf("Failed to bind CNAME and certificate: %v", err)
	}

	// Display the result.
	log.Println("Bind Certificate Success!")
}

Disassociate a certificate

If you do not want the domain name to continue using the certificate, you can disassociate the certificate from the domain name.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.  
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"

	// Add a CNAME record and set the DeleteCertificate parameter to true.
	putCnameConfig := oss.PutBucketCname{
		Cname: "www.example.com",
		CertificateConfiguration: &oss.CertificateConfiguration{
			DeleteCertificate: true,
		},
	}

	// Map a custom domain name and disassociate the certificate from the domain name.
	err = client.PutBucketCnameWithCertificate(bucketName, putCnameConfig)
	if err != nil {
		log.Fatalf("Failed to unbind CNAME and delete certificate: %v", err)
	}

	// Display the result.
	log.Println("Unbind Certificate Success!")
}

Query a CNAME record

The following sample code provides an example on how to query a CNAME record used to map a custom domain to a bucket:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.  
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"

	// Query the CNAME record. 
	cnResult, err := client.ListBucketCname(bucketName)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	var certificate oss.Certificate
	log.Printf("Bucket: %s", cnResult.Bucket)
	log.Printf("Owner: %s", cnResult.Owner)

	if len(cnResult.Cname) > 0 {
		for _, cnameInfo := range cnResult.Cname {
			// 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)
			if cnameInfo.Certificate != certificate {
				// Display the source of the certificate. 
				log.Printf("Type: %s", cnameInfo.Certificate.Type)
				// Display the ID of the certificate. 
				log.Printf("CertId: %s", cnameInfo.Certificate.CertId)
				// Display the status of the certificate. 
				log.Printf("Status: %s", cnameInfo.Certificate.Status)
				// Display the point in time when the certificate is associated with the domain name. 
				log.Printf("CreationDate: %s", cnameInfo.Certificate.CreationDate)
				// Display the signature of the certificate. 
				log.Printf("Fingerprint: %s", cnameInfo.Certificate.Fingerprint)
				// Display the point in time when the certificate takes effect. 
				log.Printf("ValidStartDate: %s", cnameInfo.Certificate.ValidStartDate)
				// Display the point in time when the certificate expires. 
				log.Printf("ValidEndDate: %s", cnameInfo.Certificate.ValidEndDate)
			}
		}
	}
}

Delete a CNAME record

The following sample code provides an example on how to delete a CNAME record used to map a custom domain to a bucket:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.  
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"
	// Specify the custom domain name. 
	cname := "www.example.com"

	// Delete the CNAME record.
	err = client.DeleteBucketCname(bucketName, cname)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Display the result.
	log.Println("Delete Bucket Cname Success!")
}

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 CreateBucketCnameToken.

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

  • For more information about the API operation that you can call to add a CNAME record to map a custom domain name to a bucket, see PutBucketCname.

  • For more information about the API operation that you can call to query the CNAME record used to map a custom domain to a bucket, see ListBucketCname.

  • For more information about the API operation that you can call to delete a CNAME record used to map a custom domain to a bucket, see DeleteBucketCname.