How to do a Pre-signed POST upload to AWS S3 in Go?

前端 未结 3 1048
借酒劲吻你
借酒劲吻你 2021-01-14 10:29

I would like to do a pre-signed POST to upload files to an AWS S3 bucket - how would this be done in Go?

Please note that this is not the same as Pre-signed upload w

3条回答
  •  别那么骄傲
    2021-01-14 11:00

    Here is an alternative approach from https://github.com/minio/minio-go that you might like for a full programmatic way of generating presigned post policy.

    package main
    
    import (
        "fmt"
        "log"
        "time"
    
        "github.com/minio/minio-go"
    )
    
    func main() {
        policy := minio.NewPostPolicy()
        policy.SetKey("myobject")
        policy.SetBucket("mybucket")
        policy.SetExpires(time.Now().UTC().AddDate(0, 0, 10)) // expires in 10 days
        config := minio.Config{
            AccessKeyID:     "YOUR-ACCESS-KEY-HERE",
            SecretAccessKey: "YOUR-PASSWORD-HERE",
            Endpoint:        "https://s3.amazonaws.com",
        }
        s3Client, err := minio.New(config)
        if err != nil {
            log.Fatalln(err)
        }
        m, err := s3Client.PresignedPostPolicy(policy)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Printf("curl ")
        for k, v := range m {
            fmt.Printf("-F %s=%s ", k, v)
        }
        fmt.Printf("-F file=@/etc/bashrc ")
        fmt.Printf(config.Endpoint + "/mybucket\n")
    }
    

    Step 1:

        policy := minio.NewPostPolicy()
        policy.SetKey("myobject")
        policy.SetBucket("mybucket")
        policy.SetExpires(time.Now().UTC().AddDate(0, 0, 10)) // expires in 10 days
    

    Instantiate a new policy structure, this policy structure implements following methods.

    func NewPostPolicy() *PostPolicy
    func (p *PostPolicy) SetBucket(bucket string) error
    func (p *PostPolicy) SetContentLength(min, max int) error
    func (p *PostPolicy) SetContentType(contentType string) error
    func (p *PostPolicy) SetExpires(t time.Time) error
    func (p *PostPolicy) SetKey(key string) error
    func (p *PostPolicy) SetKeyStartsWith(keyStartsWith string) error
    func (p PostPolicy) String() string
    

    Step 2:

        m, err := s3Client.PresignedPostPolicy(policy)
        if err != nil {
            fmt.Println(err)
            return
        }
    

    Now PresignedPostPolicy() takes the PostPolicy structure and returns back a map of "key/values" which can be used in your HTML form or curl command to upload data to s3.

提交回复
热议问题