简体   繁体   English

在 aws sdk 2 中使用 headObject 时。 为什么它给出未定义的?

[英]When using headObject in aws sdk 2 for go. Why it gives undefined?

Thanks in advance :) .提前致谢 :) 。 I'm using the following code to get metadata from an s3 object after listing all the object in a bucket .在列出存储桶中的所有对象后,我正在使用以下代码从 s3 对象获取元数据。 But I don't know why it gives the error undefined: s3.HeadObject when running go run listObjects.go -bucket xxxx -prefix xxxx但我不知道为什么它会给出错误undefined: s3.HeadObject when running go run listObjects.go -bucket xxxx -prefix xxxx

I tried two solutions: giving the client as the one created from the config and from the context as in this link appears [1].我尝试了两种解决方案:将客户端作为从配置创建的客户端,以及从上下文中创建的客户端,如此链接出现 [1]。 BUt both gave the same error.但是两者都给出了相同的错误。 Can you give me any clue?你能给我任何线索吗?

package main

import (
    "context"
    "flag"
    "fmt"
    "log"

    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

var (
    bucketName      string
    objectPrefix    string
    objectDelimiter string
    maxKeys         int
)

func init() {
    flag.StringVar(&bucketName, "bucket", "", "The `name` of the S3 bucket to list objects from.")
    flag.StringVar(&objectPrefix, "prefix", "", "The optional `object prefix` of the S3 Object keys to list.")
    flag.StringVar(&objectDelimiter, "delimiter", "",
        "The optional `object key delimiter` used by S3 List objects to group object keys.")
    flag.IntVar(&maxKeys, "max-keys", 0,
        "The maximum number of `keys per page` to retrieve at once.")
}

// Lists all objects in a bucket using pagination
func main() {
    flag.Parse()
    if len(bucketName) == 0 {
        flag.PrintDefaults()
        log.Fatalf("invalid parameters, bucket name required")
    }

    // Load the SDK's configuration from environment and shared config, and
    // create the client with this.
    cfg, err := config.LoadDefaultConfig(context.TODO())
    if err != nil {
        log.Fatalf("failed to load SDK configuration, %v", err)
    }

    client := s3.NewFromConfig(cfg)

    // Set the parameters based on the CLI flag inputs.
    params := &s3.ListObjectsV2Input{
        Bucket: &bucketName,
    }
    if len(objectPrefix) != 0 {
        params.Prefix = &objectPrefix
    }
    if len(objectDelimiter) != 0 {
        params.Delimiter = &objectDelimiter
    }

    // Create the Paginator for the ListObjectsV2 operation.
    p := s3.NewListObjectsV2Paginator(client, params, func(o *s3.ListObjectsV2PaginatorOptions) {
        if v := int32(maxKeys); v != 0 {
            o.Limit = v
        }
    })

    // Iterate through the S3 object pages, printing each object returned.
    var i int
    log.Println("Objects:")
    for p.HasMorePages() {
        i++

        // Next Page takes a new context for each page retrieval. This is where
        // you could add timeouts or deadlines.
        page, err := p.NextPage(context.TODO())
        if err != nil {
            log.Fatalf("failed to get page %v, %v", i, err)
        }

        // Log the objects found
        // Headobject function is called
        for _, obj := range page.Contents {
            
            input := &s3.HeadObjectInput{
                Bucket: &bucketName,
                Key:    obj.Key,
            }
            
            result, err := &s3.HeadObject(client, input)
            if err != nil {
                panic(err)
            }
            fmt.Println("Object:", *obj.Key)
        }
    }
}
./listObjects.go:86:20: undefined: s3.HeadObject

1 1

Doing the headObject as an auxiliary method works将 headObject 作为辅助方法有效

package main

import (
    "context"
    "flag"
    "fmt"
    "log"

    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

var (
    bucketName      string
    objectPrefix    string
    objectDelimiter string
    maxKeys         int
)

func init() {
    flag.StringVar(&bucketName, "bucket", "", "The `name` of the S3 bucket to list objects from.")
    flag.StringVar(&objectPrefix, "prefix", "", "The optional `object prefix` of the S3 Object keys to list.")
    flag.StringVar(&objectDelimiter, "delimiter", "",
        "The optional `object key delimiter` used by S3 List objects to group object keys.")
    flag.IntVar(&maxKeys, "max-keys", 0,
        "The maximum number of `keys per page` to retrieve at once.")
}

// Lists all objects in a bucket using pagination
func main() {
    flag.Parse()
    if len(bucketName) == 0 {
        flag.PrintDefaults()
        log.Fatalf("invalid parameters, bucket name required")
    }

    // Load the SDK's configuration from environment and shared config, and
    // create the client with this.
    cfg, err := config.LoadDefaultConfig(context.TODO())
    if err != nil {
        log.Fatalf("failed to load SDK configuration, %v", err)
    }

    client := s3.NewFromConfig(cfg)

    // Set the parameters based on the CLI flag inputs.
    params := &s3.ListObjectsV2Input{
        Bucket: &bucketName,
    }
    if len(objectPrefix) != 0 {
        params.Prefix = &objectPrefix
    }
    if len(objectDelimiter) != 0 {
        params.Delimiter = &objectDelimiter
    }

    // Create the Paginator for the ListObjectsV2 operation.
    p := s3.NewListObjectsV2Paginator(client, params, func(o *s3.ListObjectsV2PaginatorOptions) {
        if v := int32(maxKeys); v != 0 {
            o.Limit = v
        }
    })

    // Iterate through the S3 object pages, printing each object returned.
    var i int
    log.Println("Objects:")
    for p.HasMorePages() {
        i++

        // Next Page takes a new context for each page retrieval. This is where
        // you could add timeouts or deadlines.
        page, err := p.NextPage(context.TODO())
        if err != nil {
            log.Fatalf("failed to get page %v, %v", i, err)
        }

        // Log the objects found
        // Headobject function is called
        for _, obj := range page.Contents {
            fmt.Println("Object:", *obj.Key)
            OpHeadObject(client, bucketName, *obj.Key)
            
        }
    }
}

func OpHeadObject(sess *s3.Client, bucketName, objectName string) {
    input := &s3.HeadObjectInput{
        Bucket: &bucketName,
        Key:    &objectName,
    }
    resp, err := sess.HeadObject(context.TODO(), input)
    if err != nil {
        panic(err)
    }
        fmt.Println(resp.StorageClass) // that you want.

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Go 中的 AWS SDK。 解析数据 - AWS SDK in Go. Parsing data 集体AWS S3时的ClientError HeadObject - ClientError HeadObject when collecstatic AWS S3 AWS S3 headObject 未返回 JS SDK 中的所有元数据值 - AWS S3 headObject not returning all metadata values in JS SDK AWS Lambda:调用 HeadObject 操作时发生错误 (403):禁止 - AWS Lambda: An error occurred (403) when calling the HeadObject operation: Forbidden AWS lambda:调用 HeadObject 操作时发生错误(404):未找到 - AWS lambda:An error occurred (404) when calling the HeadObject operation: Not Found 使用 AWS Go SDK 创建客户端时出现 UnrecognizedClientException - UnrecognizedClientException when creating a client with AWS Go SDK 使用 AWS Go SDK 的动态库存 - Dynamic inventories using AWS Go SDK AWS CLI S3:使用终端在本地复制文件:致命错误:调用 HeadObject 操作时发生错误 (404) - AWS CLI S3: copying file locally using the terminal : fatal error: An error occurred (404) when calling the HeadObject operation 如何使用 Go AWS SDK 描述特定 AWS 区域中的 VPC? - How to DescribeVPCs in a particular AWS region using Go AWS SDK? 使用默认VPC以外的其他版本(aws-sdk-go)时无法调用ec2.AuthorizeSecurityGroupIngressInput - Can't call ec2.AuthorizeSecurityGroupIngressInput when using other than the default VPC (aws-sdk-go)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM