Todos os produtos
Search
Central de documentação

Object Storage Service:Proteção contra hotlink com o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) permite configurar políticas de controle de acesso baseadas em Referer, como listas de permissões e listas de bloqueios de Referer. Também é possível especificar se requisições com referrers vazios são permitidas. Assim, você evita acessos não autorizados e custos inesperados de tráfego.

Observações de uso

  • Antes de configurar a proteção contra hotlink, familiarize-se com esse recurso. Para mais informações, consulte proteção contra hotlink.

  • Os exemplos de código deste tópico usam o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o endpoint público acessa recursos em um bucket. Para acessar os recursos do bucket por meio de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre as regiões e endpoints suportados pelo Object Storage Service (OSS), consulte Regiões e endpoints do OSS.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais detalhes sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Para configurar a proteção contra hotlink ou excluir as configurações existentes em um bucket, você precisa da permissão oss:PutBucketReferer. Para consultar essas configurações, você precisa da permissão oss:GetBucketReferer. Para mais informações, consulte Conceder permissões personalizadas a usuários RAM.

Exemplos de código

Configure hotlink protection

O código abaixo demonstra como configurar a proteção 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

O exemplo a seguir mostra como consultar as configurações de proteção 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

Este trecho ilustra como excluir as configurações de proteção 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)
}

Referências

  • Para mais detalhes sobre a operação de API usada para configurar a proteção contra hotlink de um bucket, consulte PutBucketReferer.

  • Para consultar as configurações de proteção contra hotlink via API, consulte GetBucketReferer.