Todos os produtos
Search
Central de documentação

Object Storage Service:Hospedagem de site estático (back-to-origin por espelhamento) (Go SDK V2)

Última atualização: Jul 03, 2026

Configure um bucket para hospedagem de site estático e defina regras de roteamento de back-to-origin baseadas em espelhamento. Após a ativação, o OSS fornece conteúdo estático diretamente do bucket e redireciona solicitações para as páginas de índice e de erro configuradas.

Notas de uso

  • Os exemplos de código neste tópico usam o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, utiliza-se um endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter a lista completa de regiões e endpoints suportados, consulte Regiões e endpoints.

  • Os exemplos leem credenciais de acesso de variáveis de ambiente. Para instruções de configuração, consulte Configurar credenciais de acesso.

  • São necessárias as seguintes permissões do Resource Access Management (RAM):

    • oss:PutBucketWebsite: necessária para configurar a hospedagem de site estático ou o back-to-origin baseado em espelhamento.

    • oss:GetBucketWebsite: necessária para consultar configurações de hospedagem de site estático ou de back-to-origin baseado em espelhamento.

    • oss:DeleteBucketWebsite: necessária para excluir configurações de hospedagem de site estático ou de back-to-origin baseado em espelhamento.

    Para obter instruções sobre como conceder essas permissões, consulte Anexar uma política a um usuário RAM.

Hospedagem de site estático

Um site estático fornece conteúdo fixo — páginas HTML, imagens, CSS e scripts do lado do cliente — sem processamento no servidor. Esta seção aborda as três operações: PutBucketWebsite, GetBucketWebsite e DeleteBucketWebsite.

Configure

O exemplo abaixo configura um bucket para hospedagem de site estático. Ele define index.html como página de índice e error.html como página de erro 404. Salve este arquivo como put_bucket_website.go.

Para obter o exemplo completo e executável, consulte put_bucket_website.go no GitHub.

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 initializes command-line flags.
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 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 default configurations 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 configure static website hosting for the bucket.
	request := &oss.PutBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
		WebsiteConfiguration: &oss.WebsiteConfiguration{
			IndexDocument: &oss.IndexDocument{
				Suffix:        oss.Ptr("index.html"), // Set the index page to index.html.
				SupportSubDir: oss.Ptr(true),         // Enable subdirectory support.
				Type:          oss.Ptr(int64(0)),     // Type (0 indicates a static website).
			},
			ErrorDocument: &oss.ErrorDocument{
				Key:        oss.Ptr("error.html"), // Set the error page to error.html.
				HttpStatus: oss.Ptr(int64(404)),   // The HTTP status code.
			},
		},
	}

	// Send the request to configure static website hosting.
	result, err := client.PutBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket website %v", err)
	}

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

Query

O exemplo abaixo recupera a configuração de hospedagem de site estático de um bucket. Salve este arquivo como get_bucket_website.go.

Para obter o exemplo completo e executável, consulte get_bucket_website.go no GitHub.

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 initializes command-line flags.
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 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 default configurations 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 query the static website hosting configuration.
	request := &oss.GetBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
	}

	// Send the request and process the response.
	result, err := client.GetBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket website %v", err)
	}

	// Print the query result.
	log.Printf("get bucket website result:%#v\n", result)
}

Delete

O exemplo abaixo remove a configuração de hospedagem de site estático de um bucket. Salve este arquivo como delete_bucket_website.go.

Para obter o exemplo completo e executável, consulte delete_bucket_website.go no GitHub.

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 initializes command-line flags.
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 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 default configurations 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 the static website hosting configuration.
	request := &oss.DeleteBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Send the request and process the response.
	result, err := client.DeleteBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket website %v", err)
	}

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

Back-to-origin por espelhamento

O back-to-origin baseado em espelhamento foi projetado para migração de dados contínua para o OSS. Se o seu serviço estiver em execução em uma origem autogerenciada ou em outro serviço de nuvem, você poderá migrar para o OSS sem tempo de inatividade. Durante a migração, o OSS usa regras de roteamento para buscar objetos na origem sempre que um objeto solicitado ainda não tiver sido migrado, mantendo seu serviço em funcionamento sem interrupções. Esta seção aborda as três operações: PutBucketWebsite, GetBucketWebsite e DeleteBucketWebsite.

Configure

Quando um cliente solicita um objeto que não existe no bucket, o OSS pode buscá-lo em uma origem usando uma regra de roteamento de back-to-origin. Por exemplo, para um bucket na região China (Hangzhou): quando um cliente solicita um objeto ausente cuja chave começa com myobject, a regra de roteamento o busca em http://www.test.com//@filepath.

O exemplo abaixo configura essa regra de roteamento para back-to-origin baseado em espelhamento. Salve este arquivo como put_bucket_website.go.

Para obter o exemplo completo e executável, consulte put_bucket_website.go no GitHub.

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 initializes command-line flags.
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 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 default configurations and set the credentials provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Configure a routing rule.
	ruleOk := oss.RoutingRule{
		RuleNumber: oss.Ptr(int64(1)),
		Condition: &oss.RoutingRuleCondition{
			KeyPrefixEquals:             oss.Ptr("myobject"), // Specify the object key prefix for condition matching.
			HttpErrorCodeReturnedEquals: oss.Ptr(int64(404)), // The back-to-origin action is triggered when an HTTP 404 error is returned.
		},
		Redirect: &oss.RoutingRuleRedirect{
			RedirectType: oss.Ptr("Mirror"),               // Set the redirect type to Mirror.
			MirrorURL:    oss.Ptr("http://www.test.com/"), // Specify the back-to-origin URL.
			MirrorHeaders: &oss.MirrorHeaders{
				//PassAll: oss.Ptr(true),                              // Pass all headers.
				Passes:  []string{"myheader-key1", "myheader-key2"}, // Pass the specified HTTP headers.
				Removes: []string{"myheader-key3", "myheader-key4"}, // Do not pass the specified HTTP headers.
				Sets: []oss.MirrorHeadersSet{
					{
						Key:   oss.Ptr("myheader-key5"),  // Set the key for a specific HTTP header.
						Value: oss.Ptr("myheader-value"), // Set the value for a specific HTTP header.
					},
				},
			},
		},
	}

	// Create a request to configure mirroring-based back-to-origin.
	request := &oss.PutBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
		WebsiteConfiguration: &oss.WebsiteConfiguration{
			IndexDocument: &oss.IndexDocument{
				Suffix:        oss.Ptr("index.html"), // Set the index page to index.html.
				SupportSubDir: oss.Ptr(true),
				Type:          oss.Ptr(int64(0)),
			},
			ErrorDocument: &oss.ErrorDocument{
				Key:        oss.Ptr("error.html"), // Set the error page to error.html.
				HttpStatus: oss.Ptr(int64(404)),
			},
			RoutingRules: &oss.RoutingRules{
				RoutingRules: []oss.RoutingRule{
					ruleOk,
				},
			},
		},
	}

	// Send the request to configure mirroring-based back-to-origin.
	result, err := client.PutBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket website %v", err)
	}

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

Query

O exemplo abaixo recupera a configuração de back-to-origin baseado em espelhamento de um bucket. Salve este arquivo como get_bucket_website.go.

Para obter o exemplo completo e executável, consulte get_bucket_website.go no GitHub.

Importante

Se o bucket não tiver configuração de site, GetBucketWebsite retornará um erro NoSuchWebsiteConfiguration. Esse comportamento é esperado ao consultar um bucket que nunca foi configurado. Trate esse erro separadamente de outras falhas de API para evitar mascarar erros reais.

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 initializes command-line flags.
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 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 default configurations 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 query the mirroring-based back-to-origin configuration.
	request := &oss.GetBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
	}

	// Send the request and process the response.
	result, err := client.GetBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket website %v", err)
	}

	// Print the routing rules from the result.
	log.Printf("get bucket website result:%#v\n", result.WebsiteConfiguration.RoutingRules)
}

Delete

O exemplo abaixo remove a configuração de back-to-origin baseado em espelhamento de um bucket. Salve este arquivo como delete_bucket_website.go.

Para obter o exemplo completo e executável, consulte delete_bucket_website.go no GitHub.

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 initializes command-line flags.
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 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 default configurations 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 the bucket's website configuration.
	request := &oss.DeleteBucketWebsiteRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Send the request and process the response.
	result, err := client.DeleteBucketWebsite(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket website %v", err)
	}

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

Referências