content_md5.go 945 B

123456789101112131415161718192021222324252627282930313233343536
  1. package s3
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "io"
  6. "github.com/aws/aws-sdk-go/aws/awserr"
  7. "github.com/aws/aws-sdk-go/aws/request"
  8. )
  9. // contentMD5 computes and sets the HTTP Content-MD5 header for requests that
  10. // require it.
  11. func contentMD5(r *request.Request) {
  12. h := md5.New()
  13. // hash the body. seek back to the first position after reading to reset
  14. // the body for transmission. copy errors may be assumed to be from the
  15. // body.
  16. _, err := io.Copy(h, r.Body)
  17. if err != nil {
  18. r.Error = awserr.New("ContentMD5", "failed to read body", err)
  19. return
  20. }
  21. _, err = r.Body.Seek(0, 0)
  22. if err != nil {
  23. r.Error = awserr.New("ContentMD5", "failed to seek body", err)
  24. return
  25. }
  26. // encode the md5 checksum in base64 and set the request header.
  27. sum := h.Sum(nil)
  28. sum64 := make([]byte, base64.StdEncoding.EncodedLen(len(sum)))
  29. base64.StdEncoding.Encode(sum64, sum)
  30. r.HTTPRequest.Header.Set("Content-MD5", string(sum64))
  31. }