Skip to content

Commit

Permalink
compute checksum of the uploaded file for verification
Browse files Browse the repository at this point in the history
  • Loading branch information
leafo committed Nov 22, 2023
1 parent bc0533c commit f539cb1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
3 changes: 2 additions & 1 deletion zipserver/copy_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func copyHandler(w http.ResponseWriter, r *http.Request) error {
// transfer the reader to s3
// TODO: get the actual mime type from the GetFile request
log.Print("Starting transfer: ", key)
err = targetStorage.PutFile(jobCtx, config.S3Bucket, key, mReader, "application/octet-stream")
checksumMd5, err := targetStorage.PutFile(jobCtx, config.S3Bucket, key, mReader, "application/octet-stream")

if err != nil {
log.Print("Failed to copy file: ", err)
Expand All @@ -130,6 +130,7 @@ func copyHandler(w http.ResponseWriter, r *http.Request) error {
resValues.Add("Key", key)
resValues.Add("Duration", fmt.Sprintf("%.4fs", time.Since(startTime).Seconds()))
resValues.Add("Size", fmt.Sprintf("%d", mReader.BytesRead))
resValues.Add("Md5", checksumMd5)

notifyCallback(callbackURL, resValues)
})()
Expand Down
24 changes: 20 additions & 4 deletions zipserver/s3_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package zipserver

import (
"context"
"crypto/md5"
"fmt"
"io"
"net/url"
"strconv"
Expand Down Expand Up @@ -41,21 +43,35 @@ func NewS3Storage(config *Config) (*S3Storage, error) {
}, nil
}

func (c *S3Storage) PutFile(ctx context.Context, bucket, key string, contents io.Reader, mimeType string) error {
// upload file and return md5 checksum of transferred bytes
func (c *S3Storage) PutFile(ctx context.Context, bucket, key string, contents io.Reader, mimeType string) (string, error) {
uploader := s3manager.NewUploaderWithClient(s3.New(c.Session))

// Initialize a new MD5 hash.
hash := md5.New()

// Create a multi-reader that will read from the original reader and also
// perform the hash.
multi := io.TeeReader(contents, hash)

_, err := uploader.UploadWithContext(ctx, &s3manager.UploadInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
Body: contents,
Body: multi,
ContentType: aws.String(mimeType),
})

if err != nil {
return err
return "", err
}

return nil
// Compute the checksum from the hash.
checksum := hash.Sum(nil)

// Convert the checksum to a hexadecimal string.
checksumStr := fmt.Sprintf("%x", checksum)

return checksumStr, nil
}

// get some specific metadata for file
Expand Down

0 comments on commit f539cb1

Please sign in to comment.