seaweedfs/unmaintained/s3/presigned_put/presigned_put.go

76 lines
2.4 KiB
Go
Raw Normal View History

2020-08-06 11:32:05 +00:00
package main
import (
2022-08-31 07:24:17 +00:00
"crypto/md5"
"encoding/base64"
"fmt"
2020-08-06 11:32:05 +00:00
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
2022-08-31 07:24:17 +00:00
"github.com/seaweedfs/seaweedfs/weed/util"
"net/http"
2020-08-06 11:32:05 +00:00
"strings"
"time"
)
// Downloads an item from an S3 Bucket in the region configured in the shared config
// or AWS_REGION environment variable.
//
// Usage:
// go run presigned_put.go
// For this exampl to work, the domainName is needd
// weed s3 -domainName=localhost
func main() {
h := md5.New()
content := strings.NewReader(stringContent)
content.WriteTo(h)
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-east-1"),
Endpoint: aws.String("http://localhost:8333"),
})
// Create S3 service client
svc := s3.New(sess)
putRequest, output := svc.PutObjectRequest(&s3.PutObjectInput{
Bucket: aws.String("dev"),
Key: aws.String("testKey"),
})
fmt.Printf("output: %+v\n", output)
md5s := base64.StdEncoding.EncodeToString(h.Sum(nil))
putRequest.HTTPRequest.Header.Set("Content-MD5", md5s)
url, err := putRequest.Presign(15 * time.Minute)
if err != nil {
fmt.Println("error presigning request", err)
return
}
fmt.Println(url)
req, err := http.NewRequest("PUT", url, strings.NewReader(stringContent))
req.Header.Set("Content-MD5", md5s)
if err != nil {
fmt.Println("error creating request", url)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Printf("error put request: %v\n", err)
return
}
2022-08-31 07:24:17 +00:00
defer util.CloseResponse(resp)
2020-08-06 11:32:05 +00:00
fmt.Printf("response: %+v\n", resp)
}
var stringContent = `Generate a Pre-Signed URL for an Amazon S3 PUT Operation with a Specific Payload
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.
The following example adds a Body field to generate a pre-signed PUT operation that requires a specific payload to be uploaded by users.
2022-08-31 07:24:17 +00:00
`