在使用 AWS SDK 2 for Go 中的 headObject 方法时,为什么会返回 undefined?

huangapple go评论86阅读模式
英文:

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

问题

感谢您的提问。以下是您要翻译的内容:

感谢您的帮助 :)。我正在使用以下代码从存储桶中列出所有对象后获取S3对象的元数据。但是,当运行go run listObjects.go -bucket xxxx -prefix xxxx时,我不知道为什么会出现错误undefined: s3.HeadObject

我尝试了两种解决方案:将客户端设置为从配置文件创建的客户端,以及从上下文中获取客户端,就像这个链接中所示[1]。但是两者都出现了相同的错误。您能给我一些线索吗?

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", "", "要从中列出对象的S3存储桶的名称。")
	flag.StringVar(&objectPrefix, "prefix", "", "要列出的S3对象键的可选对象前缀。")
	flag.StringVar(&objectDelimiter, "delimiter", "",
		"S3 List对象使用的可选对象键分隔符。")
	flag.IntVar(&maxKeys, "max-keys", 0,
		"一次检索的最大`键数`。")
}

// 使用分页列出存储桶中的所有对象
func main() {
	flag.Parse()
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("无效的参数,需要存储桶名称")
	}

	// 从环境和共享配置中加载SDK的配置,并使用此配置创建客户端。
	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		log.Fatalf("无法加载SDK配置,%v", err)
	}

	client := s3.NewFromConfig(cfg)

	// 根据CLI标志输入设置参数。
	params := &s3.ListObjectsV2Input{
		Bucket: &bucketName,
	}
	if len(objectPrefix) != 0 {
		params.Prefix = &objectPrefix
	}
	if len(objectDelimiter) != 0 {
		params.Delimiter = &objectDelimiter
	}

	// 为ListObjectsV2操作创建Paginator。
	p := s3.NewListObjectsV2Paginator(client, params, func(o *s3.ListObjectsV2PaginatorOptions) {
		if v := int32(maxKeys); v != 0 {
			o.Limit = v
		}
	})

	// 遍历S3对象页面,打印每个返回的对象。
	var i int
	log.Println("对象:")
	for p.HasMorePages() {
		i++

		// 每个页面检索都需要一个新的上下文。在这里,您可以添加超时或截止时间。
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("无法获取第 %v 页,%v", i, err)
		}

		// 记录找到的对象
		// 调用HeadObject函数
		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("对象:", *obj.Key)
		}
	}
}
./listObjects.go:86:20: undefined: s3.HeadObject

1

英文:

Thanks in advance 在使用 AWS SDK 2 for Go 中的 headObject 方法时,为什么会返回 undefined? . I'm using the following code to get metadata from an s3 object after listing all the object in a bucket . But I don't know why it gives the error 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]. 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

得分: 1

将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", "", "要列出对象的S3存储桶的名称。")
	flag.StringVar(&objectPrefix, "prefix", "", "要列出的S3对象键的可选前缀。")
	flag.StringVar(&objectDelimiter, "delimiter", "",
		"S3 List对象用于分组对象键的可选对象键分隔符。")
	flag.IntVar(&maxKeys, "max-keys", 0,
		"一次检索的最大键数。")
}

// 使用分页列出存储桶中的所有对象
func main() {
	flag.Parse()
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("无效的参数,需要存储桶名称")
	}

	// 从环境和共享配置中加载SDK的配置,并使用此配置创建客户端。
	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		log.Fatalf("无法加载SDK配置,%v", err)
	}

	client := s3.NewFromConfig(cfg)

	// 根据CLI标志输入设置参数。
	params := &s3.ListObjectsV2Input{
		Bucket: &bucketName,
	}
	if len(objectPrefix) != 0 {
		params.Prefix = &objectPrefix
	}
	if len(objectDelimiter) != 0 {
		params.Delimiter = &objectDelimiter
	}

	// 为ListObjectsV2操作创建Paginator。
	p := s3.NewListObjectsV2Paginator(client, params, func(o *s3.ListObjectsV2PaginatorOptions) {
		if v := int32(maxKeys); v != 0 {
			o.Limit = v
		}
	})

	// 遍历S3对象页面,打印每个返回的对象。
	var i int
	log.Println("对象:")
	for p.HasMorePages() {
		i++

		// Next Page为每个页面检索提供一个新的上下文。在这里,您可以添加超时或截止日期。
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("无法获取第 %v 页,%v", i, err)
		}

		// 记录找到的对象
		// 调用HeadObject函数
		for _, obj := range page.Contents {
			fmt.Println("对象:", *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) // 你想要的。
}

希望对你有所帮助!

英文:

Doing the headObject as an auxiliary method works

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.
}

huangapple
  • 本文由 发表于 2022年7月7日 20:21:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/72897720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定