文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
GetObjectRetention
搭配 AWS SDK 或 CLI 使用
下列程式碼範例示範如何使用 GetObjectRetention
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- .NET
-
- 適用於 .NET 的 SDK
-
public async Task<ObjectLockRetention> GetObjectRetention(string bucketName,
string objectKey)
{
try
{
var request = new GetObjectRetentionRequest()
{
BucketName = bucketName,
Key = objectKey
};
var response = await _amazonS3.GetObjectRetentionAsync(request);
Console.WriteLine($"\tObject retention for {objectKey} in {bucketName}: " +
$"\n\t{response.Retention.Mode} until {response.Retention.RetainUntilDate:d}.");
return response.Retention;
}
catch (AmazonS3Exception ex)
{
Console.WriteLine($"\tUnable to fetch object lock retention: '{ex.Message}'");
return new ObjectLockRetention();
}
}
- CLI
-
- AWS CLI
-
擷取物件的物件保留組態
下列get-object-retention
範例會擷取指定物件的物件保留組態。
aws s3api get-object-retention \
--bucket amzn-s3-demo-bucket-with-object-lock
\
--key doc1.rtf
輸出:
{
"Retention": {
"Mode": "GOVERNANCE",
"RetainUntilDate": "2025-01-01T00:00:00.000Z"
}
}
- Go
-
- SDK for Go V2
-
import (
"bytes"
"context"
"errors"
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/smithy-go"
)
type S3Actions struct {
S3Client *s3.Client
S3Manager *manager.Uploader
}
func (actor S3Actions) GetObjectRetention(ctx context.Context, bucket string, key string) (*types.ObjectLockRetention, error) {
var retention *types.ObjectLockRetention
input := &s3.GetObjectRetentionInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
}
output, err := actor.S3Client.GetObjectRetention(ctx, input)
if err != nil {
var noKey *types.NoSuchKey
var apiErr *smithy.GenericAPIError
if errors.As(err, &noKey) {
log.Printf("Object %s does not exist in bucket %s.\n", key, bucket)
err = noKey
} else if errors.As(err, &apiErr) {
switch apiErr.ErrorCode() {
case "NoSuchObjectLockConfiguration":
err = nil
case "InvalidRequest":
log.Printf("Bucket %s does not have locking enabled.", bucket)
err = nil
}
}
} else {
retention = output.Retention
}
return retention, err
}
- Java
-
- SDK for Java 2.x
-
public ObjectLockRetention getObjectRetention(String bucketName, String key){
try {
GetObjectRetentionRequest retentionRequest = GetObjectRetentionRequest.builder()
.bucket(bucketName)
.key(key)
.build();
GetObjectRetentionResponse response = getClient().getObjectRetention(retentionRequest);
System.out.println("tObject retention for "+key +" in "+ bucketName +": " + response.retention().mode() +" until "+ response.retention().retainUntilDate() +".");
return response.retention();
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
return null;
}
}
- JavaScript
-
- SDK for JavaScript (v3)
-
import {
GetObjectRetentionCommand,
S3Client,
S3ServiceException,
} from "@aws-sdk/client-s3";
export const main = async ({ bucketName, key }) => {
const client = new S3Client({});
try {
const { Retention } = await client.send(
new GetObjectRetentionCommand({
Bucket: bucketName,
Key: key,
}),
);
console.log(
`${key} in ${bucketName} will be retained until ${Retention.RetainUntilDate}`,
);
} catch (caught) {
if (
caught instanceof S3ServiceException &&
caught.name === "NoSuchObjectLockConfiguration"
) {
console.warn(
`The object "${key}" in the bucket "${bucketName}" does not have an ObjectLock configuration.`,
);
} else if (caught instanceof S3ServiceException) {
console.error(
`Error from S3 while getting object retention settings for "${bucketName}". ${caught.name}: ${caught.message}`,
);
} else {
throw caught;
}
}
};
import { parseArgs } from "node:util";
import {
isMain,
validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";
const loadArgs = () => {
const options = {
bucketName: {
type: "string",
required: true,
},
key: {
type: "string",
required: true,
},
};
const results = parseArgs({ options });
const { errors } = validateArgs({ options }, results);
return { errors, results };
};
if (isMain(import.meta.url)) {
const { errors, results } = loadArgs();
if (!errors) {
main(results.values);
} else {
console.error(errors.join("\n"));
}
}
- PowerShell
-
- Tools for PowerShell
-
範例 1: 命令會傳回模式和日期,直到保留物件為止。
Get-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt'