All Products
Search
Document Center

Object Storage Service:Prevent objects with the same name from being overwritten (Go SDK V1)

Last Updated:Nov 28, 2025

By default, if you upload an object that has the same name as an existing object, the existing object is overwritten by the uploaded object. This topic describes how to configure the x-oss-forbid-overwrite request header to prevent existing objects from being overwritten by objects with the same names when you copy objects or perform simple upload or multipart upload.

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 and endpoints.

  • 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 Configure OSSClient instances.

Sample code

The following sample code provides an example on how to prevent existing objects from being overwritten by objects that have the same names when you perform simple upload:

package main

import (
	"log"
	"strings"

	"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.
	// Set yourEndpoint to the endpoint of the bucket's region. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set 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)
	}

	// Set yourBucketName to the name of the bucket.
	bucketName := "yourBucketName"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify whether to overwrite an object with the same name.
	// If you do not specify oss.ForbidOverWrite, an object with the same name is overwritten by default.
	// If you set oss.ForbidOverWrite to false, an object with the same name is overwritten.
	// If you set oss.ForbidOverWrite to true, an object with the same name is not overwritten. If an object with the same name exists, the program reports an error.
	forbidWrite := oss.ForbidOverWrite(true)

	// Upload a string.
	// Set yourObjectName to the full path of the object. Do not include the bucket name in the full path.
	objectName := "yourObjectName"
	objectValue := "yourObjectValue"
	err = bucket.PutObject(objectName, strings.NewReader(objectValue), forbidWrite)
	if err != nil {
		log.Fatalf("Failed to upload object '%s': %v", objectName, err)
	}

	log.Printf("Successfully uploaded object '%s' with value '%s'", objectName, objectValue)
}

Common scenarios

Prevent an object from being overwritten when you copy it

The following sample code shows how to prevent a copied object from overwriting an existing object with the same 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.
	// Set yourEndpoint to the endpoint of the bucket's region. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set 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)
	}

	// Set yourBucketName to the name of the bucket.
	bucketName := "yourBucketName"
	// Set yourObjectName to the full path of the source object. Do not include the bucket name in the full path.
	objectName := "yourObjectName"
	// Set yourDestObjectName to the full path of the destination object. Do not include the bucket name in the full path.
	destObjectName := "yourDestObjectName"

	// Get the bucket instance.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify whether to overwrite the destination object if it has the same name.
	// If you do not specify oss.ForbidOverWrite, a destination object with the same name is overwritten by default.
	// If you set oss.ForbidOverWrite to false, a destination object with the same name is overwritten.
	// If you set oss.ForbidOverWrite to true, a destination object with the same name is not overwritten. If a destination object with the same name exists, the program reports an error.
	forbidWrite := oss.ForbidOverWrite(true)

	// Copy the object to another object in the same bucket.
	_, err = bucket.CopyObject(objectName, destObjectName, forbidWrite)
	if err != nil {
		log.Fatalf("Failed to copy object from '%s' to '%s': %v", objectName, destObjectName, err)
	}

	log.Printf("Successfully copied object from '%s' to '%s'", objectName, destObjectName)
}

Prevent an object from being overwritten during a multipart upload

The following sample code shows how to prevent an object from being overwritten during a multipart upload:

package main

import (
	"log"
	"os"

	"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.
	// Set yourEndpoint to the endpoint of the bucket's region. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set 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)
	}

	// Set yourBucketName to the name of the bucket.
	bucketName := "yourBucketName"
	// Set yourObjectName to the full path of the object. Do not include the bucket name in the full path.
	objectName := "yourObjectName"
	// Set yourLocalFilename to the full path of the local file.
	localFilename := "yourLocalFilename"

	// Get the bucket instance.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Split the file into multiple parts.
	chunks, err := oss.SplitFileByPartNum(localFilename, 3)
	if err != nil {
		log.Fatalf("Failed to split file: %v", err)
	}

	// Open the local file.
	fd, err := os.Open(localFilename)
	if err != nil {
		log.Fatalf("Failed to open local file '%s': %v", localFilename, err)
	}
	defer fd.Close()

	// Specify whether to overwrite an object with the same name.
	// If you do not specify oss.ForbidOverWrite, an object with the same name is overwritten by default.
	// If you set oss.ForbidOverWrite to false, an object with the same name is overwritten.
	// If you set oss.ForbidOverWrite to true, an object with the same name is not overwritten. If an object with the same name exists, the program reports an error.
	forbidWrite := oss.ForbidOverWrite(true)

	// Step 1: Initiate a multipart upload event.
	imur, err := bucket.InitiateMultipartUpload(objectName, forbidWrite)
	if err != nil {
		log.Fatalf("Failed to initiate multipart upload for '%s': %v", objectName, err)
	}

	// Step 2: Upload parts.
	var parts []oss.UploadPart
	for _, chunk := range chunks {
		fd.Seek(chunk.Offset, os.SEEK_SET)
		// Call the UploadPart method to upload each part.
		part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number)
		if err != nil {
			log.Fatalf("Failed to upload part %d of '%s': %v", chunk.Number, objectName, err)
		}
		parts = append(parts, part)
	}

	// Step 3: Complete the multipart upload and prevent the object from being overwritten.
	cmur, err := bucket.CompleteMultipartUpload(imur, parts, forbidWrite)
	if err != nil {
		log.Fatalf("Failed to complete multipart upload for '%s': %v", objectName, err)
	}

	log.Printf("Multipart upload completed successfully for '%s'. cmur: %v", objectName, cmur)
}

References