-
翻翻过去那场雪
确保您具有以下权限:“s3:GetObject”、“s3:ListBucket”、关于安全性,AWS刚刚为S3引入了强一致性s3svc = s3.New(sess) func keyExists(bucket string, key string) (bool, error) { _, err := s3svc.HeadObject(&s3.HeadObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), }) if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case "NotFound": // s3.ErrCodeNoSuchKey does not work, aws is missing this error code so we hardwire a string return false, nil default: return false, err } } return false, err } return true, nil }
-
隔江千里
如果您使用适用于 Go V2 的 AWS 开发工具包:import ( ... awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" ...)func uploaded(ctx context.Context, client *s3.Client, bucket string, key string) (bool, error) { _, err := client.HeadObject(ctx, &s3.HeadObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), }) if err != nil { var responseError *awshttp.ResponseError if errors.As(err, &responseError) && responseError.ResponseError.HTTPStatusCode() == http.StatusNotFound { return false, nil } return false, err } return true, nil}
-
慕容3067478
您可以尝试使用以下代码来获取对象元数据:sess, err := session.NewSession(&aws.Config{ Region: aws.String("your-region"),})if err != nil { //handle error here}svc := s3.New(session.Must(sess, err))output, err := svc.HeadObject(&s3.HeadObjectInput{ Bucket: aws.String("bucket_name"), Key: aws.String("object_key"),})if err != nil { //handle error here}fmt.Println(output.LastModified) //do something with metadata
-
偶然的你
只需参考 AWS API S3 HeadObject 方法:AWS API 文档。如果缺少对象,它将返回状态代码 404。HEAD 请求与对象上的 GET 操作具有相同的选项。该响应与 GET 响应相同,只是没有响应正文。因此,如果 HEAD 请求生成错误,它会返回通用的 404 Not Found 或 403 Forbidden 代码。import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" "log")func IsObjectExistsInS3Bucket(bucketName string, objectKey string) bool{ _, err := executeHeadObjectMethodOnS3Api(bucketName, objectKey) return ! handleErrorOnS3HeadObjectAction(bucketName, objectKey, err)}func executeHeadObjectMethodOnS3Api(bucketName string, objectKey string) (output *s3.HeadObjectOutput, err error){ s3Client := getS3Client() return s3Client.HeadObject(context.TODO(), &s3.HeadObjectInput{ Bucket: aws.String(bucketName), Key: aws.String(objectKey), })}func handleErrorOnS3HeadObjectAction(bucketName, objectKey string, err error) (hit bool){ logUnableToHeadObjectFromS3Bucket(bucketName, objectKey, err) return err != nil}func logUnableToHeadObjectFromS3Bucket(bucketName string, objectKey string, err error) { if err != nil { log.Printf("Unable to head object {%s} from S3 bucket {%s}: { %v }", objectKey, bucketName, err) }}