presigned_put.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "net/http"
  10. "strings"
  11. "time"
  12. util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
  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. util_http.InitGlobalHttpClient()
  23. h := md5.New()
  24. content := strings.NewReader(stringContent)
  25. content.WriteTo(h)
  26. // Initialize a session in us-west-2 that the SDK will use to load
  27. // credentials from the shared credentials file ~/.aws/credentials.
  28. sess, err := session.NewSession(&aws.Config{
  29. Region: aws.String("us-east-1"),
  30. Endpoint: aws.String("http://localhost:8333"),
  31. })
  32. // Create S3 service client
  33. svc := s3.New(sess)
  34. putRequest, output := svc.PutObjectRequest(&s3.PutObjectInput{
  35. Bucket: aws.String("dev"),
  36. Key: aws.String("testKey"),
  37. })
  38. fmt.Printf("output: %+v\n", output)
  39. md5s := base64.StdEncoding.EncodeToString(h.Sum(nil))
  40. putRequest.HTTPRequest.Header.Set("Content-MD5", md5s)
  41. url, err := putRequest.Presign(15 * time.Minute)
  42. if err != nil {
  43. fmt.Println("error presigning request", err)
  44. return
  45. }
  46. fmt.Println(url)
  47. req, err := http.NewRequest("PUT", url, strings.NewReader(stringContent))
  48. req.Header.Set("Content-MD5", md5s)
  49. if err != nil {
  50. fmt.Println("error creating request", url)
  51. return
  52. }
  53. resp, err := http.DefaultClient.Do(req)
  54. if err != nil {
  55. fmt.Printf("error put request: %v\n", err)
  56. return
  57. }
  58. defer util_http.CloseResponse(resp)
  59. fmt.Printf("response: %+v\n", resp)
  60. }
  61. var stringContent = `Generate a Pre-Signed URL for an Amazon S3 PUT Operation with a Specific Payload
  62. 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.
  63. The following example adds a Body field to generate a pre-signed PUT operation that requires a specific payload to be uploaded by users.
  64. `