You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.3 KiB

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