4 回答
TA贡献2065条经验 获得超13个赞
确保您具有以下权限:“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
}
TA贡献1906条经验 获得超10个赞
如果您使用适用于 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
}
TA贡献1773条经验 获得超3个赞
您可以尝试使用以下代码来获取对象元数据:
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
TA贡献1841条经验 获得超3个赞
只需参考 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)
}
}
- 4 回答
- 0 关注
- 140 浏览
添加回答
举报