presigned_put.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "fmt"
  6. "github.com/aws/aws-sdk-go/aws"
  7. "github.com/aws/aws-sdk-go/aws/session"
  8. "github.com/aws/aws-sdk-go/service/s3"
  9. "github.com/seaweedfs/seaweedfs/weed/util"
  10. "net/http"
  11. "strings"
  12. "time"
  13. )
  14. // Downloads an item from an S3 Bucket in the region configured in the shared config
  15. // or AWS_REGION environment variable.
  16. //
  17. // Usage:
  18. // go run presigned_put.go
  19. // For this exampl to work, the domainName is needd
  20. // weed s3 -domainName=localhost
  21. func main() {
  22. h := md5.New()
  23. content := strings.NewReader(stringContent)
  24. content.WriteTo(h)
  25. // Initialize a session in us-west-2 that the SDK will use to load
  26. // credentials from the shared credentials file ~/.aws/credentials.
  27. sess, err := session.NewSession(&aws.Config{
  28. Region: aws.String("us-east-1"),
  29. Endpoint: aws.String("http://localhost:8333"),
  30. })
  31. // Create S3 service client
  32. svc := s3.New(sess)
  33. putRequest, output := svc.PutObjectRequest(&s3.PutObjectInput{
  34. Bucket: aws.String("dev"),
  35. Key: aws.String("testKey"),
  36. })
  37. fmt.Printf("output: %+v\n", output)
  38. md5s := base64.StdEncoding.EncodeToString(h.Sum(nil))
  39. putRequest.HTTPRequest.Header.Set("Content-MD5", md5s)
  40. url, err := putRequest.Presign(15 * time.Minute)
  41. if err != nil {
  42. fmt.Println("error presigning request", err)
  43. return
  44. }
  45. fmt.Println(url)
  46. req, err := http.NewRequest("PUT", url, strings.NewReader(stringContent))
  47. req.Header.Set("Content-MD5", md5s)
  48. if err != nil {
  49. fmt.Println("error creating request", url)
  50. return
  51. }
  52. resp, err := http.DefaultClient.Do(req)
  53. if err != nil {
  54. fmt.Printf("error put request: %v\n", err)
  55. return
  56. }
  57. defer util.CloseResponse(resp)
  58. fmt.Printf("response: %+v\n", resp)
  59. }
  60. var stringContent = `Generate a Pre-Signed URL for an Amazon S3 PUT Operation with a Specific Payload
  61. You can generate a pre-signed URL for a PUT operation that checks whether users upload the correct content. When the SDK pre-signs a request, it computes the checksum of the request body and generates an MD5 checksum that is included in the pre-signed URL. Users must upload the same content that produces the same MD5 checksum generated by the SDK; otherwise, the operation fails. This is not the Content-MD5, but the signature. To enforce Content-MD5, simply add the header to the request.
  62. The following example adds a Body field to generate a pre-signed PUT operation that requires a specific payload to be uploaded by users.
  63. `