英文:
Get aws ec2 instance metadata using go sdk v2
问题
我尝试了这个例子:
https://aws.github.io/aws-sdk-go-v2/docs/sdk-utilities/ec2-imds/
并且 go.mod 使用的是:
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.15
但是 localip 打印的结果是:
&{{0xc0002d1680} {map[{}:{[{<nil> false false {map[]}}]}]}}
有人成功运行过吗?
英文:
I try this example:
https://aws.github.io/aws-sdk-go-v2/docs/sdk-utilities/ec2-imds/
and go.mod is using:
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.15
but the localip prints as:
&{{0xc0002d1680} {map[{}:{[{<nil> false false {map[]}}]}]}}
Anyone have this working?
答案1
得分: 1
这是解决问题的方法,如果有人感兴趣,可以参考这个链接:https://github.com/natemarks/ec2metadata
英文:
This solves the problem if anyone is interested:
https://github.com/natemarks/ec2metadata
答案2
得分: 0
client.GetMetadata函数返回一个GetMetadataOutput对象,其中包含一个Content元素,该元素是类型为io.Reader的HTTP resp.Body。该元素还需要进一步转换为字符串,例如通过以下函数:
func copyToString(r io.Reader) (res string, err error) {
var sb strings.Builder
if _, err = io.Copy(&sb, r); err == nil {
res = sb.String()
}
return
}
因此,AWS示例的正确版本应该返回:
localip_str, err := copyToString(localip.Content)
英文:
The client.GetMetadata function returns a GetMetadataOutput object with a Content element which is the HTTP resp.Body of type io.Reader. That element needs to be additionally converted to a string, e.g., via a function like this
func copyToString(r io.Reader) (res string, err error) {
var sb strings.Builder
if _, err = io.Copy(&sb, r); err == nil {
res = sb.String()
}
return
}
So, a correct version of the AWS sample should return
localip_str, err := copyToString(localip.Content)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论