All Products
Search
Document Center

Object Storage Service:Hosting situs web statis (pengembalian ke sumber berbasis mirroring) (Go SDK V2)

Last Updated:Apr 03, 2026

Anda dapat mengonfigurasi bucket untuk hosting situs web statis dan menetapkan aturan routing untuk pengembalian ke sumber berbasis mirroring. Setelah hosting situs web statis diaktifkan, permintaan akan dilayani langsung dari bucket dan secara otomatis dialihkan ke halaman indeks serta halaman error yang telah ditentukan.

Usage notes

  • Contoh kode dalam topik ini menggunakan ID wilayah cn-hangzhou, yang sesuai dengan wilayah China (Hangzhou). Secara default, titik akhir publik digunakan. Jika Anda ingin mengakses OSS dari layanan Alibaba Cloud lainnya di wilayah yang sama, gunakan titik akhir internal. Untuk informasi selengkapnya mengenai wilayah dan titik akhir yang didukung OSS, lihat Regions and endpoints.

  • Contoh dalam topik ini memperoleh kredensial akses dari variabel lingkungan. Untuk informasi selengkapnya tentang cara mengonfigurasi kredensial akses, lihat Configure access credentials.

  • Untuk mengonfigurasi hosting situs web statis atau pengembalian ke sumber berbasis mirroring, Anda harus memiliki izin oss:PutBucketWebsite. Untuk menanyakan konfigurasi hosting situs web statis atau pengembalian ke sumber berbasis mirroring, Anda harus memiliki izin oss:GetBucketWebsite. Untuk menghapus konfigurasi tersebut, Anda harus memiliki izin oss:DeleteBucketWebsite. Untuk informasi selengkapnya, lihat Attach a policy to a RAM user.

Static website hosting

Situs web statis terdiri dari konten statis, seperti halaman web dan skrip sisi klien seperti JavaScript.

Configure

Kode berikut menunjukkan cara mengonfigurasi hosting situs web statis:

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

Kode berikut menunjukkan cara menanyakan konfigurasi hosting situs web statis:

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

Kode berikut menunjukkan cara menghapus konfigurasi hosting situs web statis:

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)
}

Mirroring back-to-origin

Pengembalian ke sumber berbasis mirroring terutama digunakan untuk migrasi data yang mulus ke OSS. Misalnya, jika layanan Anda berjalan di origin yang dikelola sendiri atau produk cloud lainnya, Anda dapat memigrasikan layanan tersebut ke OSS tanpa gangguan. Selama proses migrasi, Anda dapat menggunakan aturan routing untuk pengembalian ke sumber berbasis mirroring guna mengambil data yang belum dimigrasikan ke OSS, sehingga menjamin kelangsungan bisnis.

Configure

Ketika klien meminta objek yang tidak ada di bucket, Anda dapat menentukan kondisi pengembalian ke sumber dan URL pengembalian ke sumber untuk mengambil objek tersebut dari origin. Misalnya, untuk bucket di wilayah China (Hangzhou), jika klien meminta objek yang tidak ada dengan kunci yang diawali myobject, Anda dapat mengonfigurasi aturan routing untuk mengambil objek tersebut dari http://www.test.com/.

Kode berikut menunjukkan cara mengonfigurasi aturan routing untuk pengembalian ke sumber berbasis mirroring dalam skenario ini:

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

Kode berikut menunjukkan cara menanyakan konfigurasi pengembalian ke sumber berbasis mirroring:

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

Kode berikut menunjukkan cara menghapus konfigurasi pengembalian ke sumber berbasis mirroring:

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)
}

References