【问题标题】:Amazon S3 cannot call API because of no such host error由于没有此类主机错误,Amazon S3 无法调用 API
【发布时间】:2021-06-07 20:53:00
【问题描述】:

我正在尝试在 GoLang 中构建 Amazon S3 客户端,但在进行 API 调用时遇到了问题。我收到一条错误消息,提示“没有这样的主机”,但我确信我提供的凭据是正确的。

定义一个结构来保存客户端

// the Client struct holding the client itself as  well as the bucket.
type S3Client struct {
    S3clientObject s3.S3
    bucket string
}

// Initialize the client
func CreateS3Client() S3Client{
     S3clientCreate := S3Client{S3clientObject: Connect(), bucket: GetS3Bucket()}
     if (!CheckBuckets(S3clientCreate)) {
         exitErrorf("Bucket does not exist, try again.")
     }
     return S3clientCreate
}

连接到存储桶

func Connect() s3.S3{
    // Initialize a session
    
    sess, err := session.NewSession(&aws.Config{
        Credentials: credentials.NewStaticCredentials("myCredentials", "myCreds", ""),
        Endpoint:    aws.String("myDomain"),
        Region:      aws.String("myRegion"),
    },
    )
    if err != nil {
        exitErrorf("Unable to use credentials, %v", err)
    }
    // Create S3 service client
    svc := s3.New(sess)
    return *svc
}

此时,我可以建立连接并使用 ListBuckets 功能接收所有存储桶的列表(例如:https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.ListBuckets

当我尝试调用 GetObject API 时,它告诉我找不到主机

// Gets an object from the bucket
func Get(client S3Client, key string) interface{} {
    
    // golang does not support "default values" so I used a nil (same as null)
    if (key == "") {
        return nil
    }

    svc := client.S3clientObject
    input := &s3.GetObjectInput{
        Bucket: aws.String("myBucket"),
        Key: aws.String("myPathKey"),
    }

    result, err := svc.GetObject(input)
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            case s3.ErrCodeNoSuchKey:
                fmt.Println(s3.ErrCodeNoSuchKey, aerr.Error())
            case s3.ErrCodeInvalidObjectState:
                fmt.Println(s3.ErrCodeInvalidObjectState, aerr.Error())
            default:
                fmt.Println(aerr.Error())  
            }
        } else {
            fmt.Println(err.Error())
        }
    }

    return result
}

这会返回:

dial tcp: lookup "hostname": no such host

我无法弄清楚为什么会发生这种情况,因为我能够成功连接到存储桶,并使用 ListBuckets 将它们列出,但是当使用另一个 API 调用时,它无法找到主机。我的代码有问题吗?还有其他我忘记的配置吗?

非常感谢任何帮助或指导,因为我对使用 GoLang 和 S3 有点陌生。

【问题讨论】:

  • 您可以按照以下示例进行操作:github.com/aws/aws-sdk-go/blob/main/example/service/s3/… 代码似乎没问题,但很难判断,因为很多事情都可能出错。我认为您应该使用调试器来缩小问题范围。或向我们提供更多详细信息
  • @SaurabhNigam 您还需要什么详细信息?很遗憾,我无法共享凭据或主机名,但我已经三次检查它们是否准确。

标签: amazon-web-services go amazon-s3 bucket


【解决方案1】:

显然问题出在存储桶名称上。我为解决这个问题所做的只是在创建它时在存储桶名称前面加上一个“/”并且它起作用了。

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多