Search code examples
goaws-sdk-go

Go can't set string to struct


This code is get all objects from s3 and delete objects.
getAllObjects is called from DeletePhotosFromS3.

I cloud get 2 different keys in objects that is in DeletePhotosFromS3.
But deleteObjects have 2 same keys. ex [{Key: 1}, {Key: 1}].

Why deleteObjects have 2 same keys and how to set objects in []*s3.ObjectIdentifier?

func getAllObject(userID string) (*[]string, error) {
    var objects []string

    svc := initS3()
    config := model.NewConfig()

    input := &s3.ListObjectsInput{
        Bucket:  aws.String(config.AWSS3Bucket),
        Prefix:  aws.String(userID),
        MaxKeys: aws.Int64(2), // default 1000
    }

    result, err := svc.ListObjects(input)
    if err != nil {
        return &objects, err
    }

    for _, v := range result.Contents {
        objects = append(objects, *v.Key)
    }

    return &objects, nil
}

func DeletePhotosFromS3(userID string) (error) {
    var deleteObjects []*s3.ObjectIdentifier

    svc := initS3()
    config := model.NewConfig()

    objects, err := getAllObject(userID) // called getAllObject
    for _, v := range *objects {
        deleteObjects = append(deleteObjects, &s3.ObjectIdentifier{Key: &v}) // Er
    }
    ... 
}

Solution

  • The iteration value v in your for loop is reused for each iteration. The Pointer &v will be the same for each item appended to the list. Fixed snippet:

    for _, v := range *objects {
            vcopy := v
            deleteObjects = append(deleteObjects, &s3.ObjectIdentifier{Key: &vcopy})
    }