Todos los productos
Search
Centro de documentos

Object Storage Service:Protección contra hotlink con OSS SDK for Go 2.0

Última actualización: Sep 24, 2026

Object Storage Service (OSS) le permite configurar políticas de control de acceso basadas en Referer, como las listas blancas y negras de Referer. También puede especificar si se permiten las solicitudes con referrers vacíos. Así, evita los accesos no autorizados y los cargos inesperados por tráfico.

Notas de uso

  • Antes de configurar la protección contra hotlink, familiarícese con esta función. Para obtener más información, consulte hotlink protection.

  • El código de ejemplo de este tema utiliza el identificador de región cn-hangzhou, correspondiente a China (Hangzhou). De forma predeterminada, se usa el endpoint público para acceder a los recursos de un bucket. Si desea acceder a los recursos del bucket mediante otros servicios de Alibaba Cloud ubicados en la misma región que el bucket, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles con Object Storage Service (OSS), consulte OSS regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.

  • Para configurar la protección contra hotlink de un bucket o eliminar su configuración, necesita el permiso oss:PutBucketReferer. Para consultar la configuración de protección contra hotlink, necesita el permiso oss:GetBucketReferer. Para obtener más información, consulte Grant custom permissions to RAM users.

Código de ejemplo

Configure hotlink protection

A continuación se muestra un ejemplo de cómo configurar la protección contra hotlink.

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 your bucket is located.
	bucketName string // Name of your 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 your 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 configure hotlink protection for your bucket.
	request := &oss.PutBucketRefererRequest{
		Bucket: oss.Ptr(bucketName), // Name of your bucket.
		RefererConfiguration: &oss.RefererConfiguration{
			AllowEmptyReferer: oss.Ptr(true),
			RefererList: &oss.RefererList{
				Referers: []string{
					"http://www.aliyun.com",
					"https://www.aliyun.com",
					"https://www.www.alibabacloud.com/help",
					"http://www.?.aliyuncs.com",
				},
			}, // Add Referers to the Referer whitelist. You can use asterisks (*) and question marks (?) as wildcard characters in Referers.
			RefererBlacklist: &oss.RefererBlacklist{
				Referers: []string{
					"http://www.refuse.com",
					"https://*.hack.com",
					"http://ban.*.com",
					"https://www.?.deny.com",
				},
			}, // Add Referers to the Referer blacklist.
		},
	}

	// Process the request of configuring hotlink protection for the bucket.
	result, err := client.PutBucketReferer(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket referer %v", err)
	}

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

Query configurations of hotlink protection

A continuación se muestra un ejemplo de cómo consultar la configuración de protección contra hotlink.

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 your bucket is located.
	bucketName string // Name of your 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 your 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 configurations of hotlink protection.
	request := &oss.GetBucketRefererRequest{
		Bucket: oss.Ptr(bucketName), // Name of your bucket.
	}

	// Process the query request.
	result, err := client.GetBucketReferer(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket referer %v", err)
	}

	// Display the result.
	log.Printf("get bucket referer result:%#v\n", result.RefererConfiguration.RefererList.Referers)
}

Delete configurations of hotlink protection

A continuación se muestra un ejemplo de cómo eliminar la configuración de protección contra hotlink.

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 your bucket is located.
	bucketName string // Name of your 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 your 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 configure hotlink protection.
	request := &oss.PutBucketRefererRequest{
		Bucket: oss.Ptr(bucketName), // Name of your bucket.
		RefererConfiguration: &oss.RefererConfiguration{
			AllowEmptyReferer: oss.Ptr(true),
			RefererList: &oss.RefererList{
				Referers: []string{}, // No specific Referer restrictions are applied。
			},
		},
	}

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

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

Referencias

  • Para obtener más información sobre la operación de API que permite configurar la protección contra hotlink de un bucket, consulte PutBucketReferer.

  • Para obtener más información sobre la operación de API que permite consultar la configuración de protección contra hotlink, consulte GetBucketReferer.