Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can safely check if file exists in S3 bucket using go in lambda?

I am working on a service for my project that is used to synchronize Lambdas works in AWS. The idea is to write a TrackerFile module that will store structures on S3. Each time I use the tracker, I will check if there is a file with the name assigned to the called tracker.

I have no idea but how to safely check if a file with a given name exists on S3. can you show a sample piece of code that would be able to return (bool, err) where bool is True if the file exists?

like image 626
R.Slaby Avatar asked Dec 10 '22 02:12

R.Slaby


1 Answers

Make sure you have the following permissions: "s3:GetObject", "s3:ListBucket",

Regarding Safety, AWS just introduced strong consistency for S3

s3svc = s3.New(sess)
     
func keyExists(bucket string, key string) (bool, error) {
        _, err := s3svc.HeadObject(&s3.HeadObjectInput{
            Bucket: aws.String(bucket),
            Key:    aws.String(key),
        })
        if err != nil {
            if aerr, ok := err.(awserr.Error); ok {
                switch aerr.Code() {            
                case "NotFound": // s3.ErrCodeNoSuchKey does not work, aws is missing this error code so we hardwire a string
                    return false, nil
                default:
                    return false, err
                }
            }
            return false, err
        }
        return true, nil
    }
like image 106
Ioannis Tsiokos Avatar answered May 11 '23 12:05

Ioannis Tsiokos