Skip to content

Instantly share code, notes, and snippets.

@hernanhrm
Created July 16, 2022 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hernanhrm/3b6343bcc026b1bbaf92b90accc276e1 to your computer and use it in GitHub Desktop.
Save hernanhrm/3b6343bcc026b1bbaf92b90accc276e1 to your computer and use it in GitHub Desktop.
type GetFileResponse struct {
FileBytes []byte
ContentType string
}
// GetFile returns a file from the s3 bucket
func (s Service) GetFile(filename string) (GetFileResponse, error) {
input := &s3.GetObjectInput{
Bucket: aws.String(s.Bucket),
Key: aws.String(filename),
}
result, err := s.S3.GetObject(input)
if err != nil {
if aswErr, ok := err.(awserr.Error); ok {
switch aswErr.Code() {
case s3.ErrCodeNoSuchKey:
return GetFileResponse{}, fmt.Errorf("s3.GetFile: file does not exists")
default:
return GetFileResponse{}, fmt.Errorf("s3.GetFile: %w", err)
}
}
return GetFileResponse{}, fmt.Errorf("s3.GetFile: %w", err)
}
defer result.Body.Close()
// we need the file content type and bytes to return the file with echo (web framework)
m := GetFileResponse{}
fileBytes, err := io.ReadAll(result.Body)
if err != nil {
return GetFileResponse{}, fmt.Errorf("s3.GetFile.io.ReadAll(): %w", err)
}
m.FileBytes = fileBytes
if result.ContentType != nil {
m.ContentType = *result.ContentType
}
return m, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment