Search code examples
filegoamazon-s3aws-lambda

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?


Solution

  • To ensure compatibility across AWS SDK v3 and AWS SDK v2 I would recommend using both the 404 and the "NotFound" code.

    export async function fileExistsInS3(bucket, key) {
        try {
            await s3.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));
            return { fileExists: true };
        } catch (error) {
            if (error.code === 'NotFound' || (error['$fault'] === 'client' && error['$metadata']?.httpStatusCode === 404)) {
                return { fileExists: false };
            }
            throw error; 
        }
    }
    

    EDIT: here is the Go version, as requested by Md. A. Apu.

    func fileExistsInS3(client *s3.Client, bucket, key string) (bool, error) {
        _, err := client.HeadObject(context.TODO(), &s3.HeadObjectInput{
            Bucket: aws.String(bucket),
            Key:    aws.String(key),
        })
        if err != nil {
            var responseError *awshttp.ResponseError
            if errors.As(err, &responseError) && responseError.ResponseError.HTTPStatusCode() == http.StatusNotFound {
                return false, nil
            }
            return false, err
        }
        return true, nil
    }