Home  >  Article  >  Backend Development  >  How to Perform a Pre-signed POST Upload to AWS S3 using Go?

How to Perform a Pre-signed POST Upload to AWS S3 using Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-23 01:01:14319browse

How to Perform a Pre-signed POST Upload to AWS S3 using Go?

Performing a Pre-signed POST Upload to AWS S3 in Go

In this guide, we will delve into the specifics of performing a pre-signed POST upload to an AWS S3 bucket using Go. This approach differs from the more common pre-signed upload mechanism involving PUT.

Prerequisites:

  1. Configure your S3 bucket to allow public download access by setting the appropriate bucket policy.
  2. Construct a POST policy that permits the file upload, specifying the bucket, key, expiration time, access control list (ACL), and other necessary parameters.
  3. Generate and sign the POST policy using the credentials of the S3 bucket owner. This involves base64 encoding, HMAC-SHA256 hash calculation, and hex encoding.

Multipart Form Data Construction and POST Request:

To initiate the upload, prepare a multipart form data request containing all the fields specified in the policy, including the signed policy document, key, and file content. Use the CreateFormField method of the multipart package to create each form field.

Code Example:

Here is a Go code snippet that outlines the process:

func Upload(url string, fields Fields) error {
    var b bytes.Buffer
    w := multipart.NewWriter(&b)
    for _, f := range fields {
        fw, err := w.CreateFormField(f.Key)
        if err != nil {
            return err
        }
        if _, err := fw.Write([]byte(f.Value)); err != nil {
            return err
        }
    }
    w.Close()

    req, err := http.NewRequest("POST", url, &b)
    if err != nil {
        return err
    }
    req.Header.Set("Content-Type", w.FormDataContentType())

    client := &http.Client{}
    res, err := client.Do(req)
    if err != nil {
        return err
    }
    if res.StatusCode != http.StatusOK {
        err = fmt.Errorf("bad status: %s", res.Status)
    }
    return nil
}

By following these steps, you can seamlessly upload files to an AWS S3 bucket using the pre-signed POST method in Go.

The above is the detailed content of How to Perform a Pre-signed POST Upload to AWS S3 using Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn