使用Go 預簽核POST 上傳到AWS S3
為了將檔案安全上傳到AWS S3 儲存桶,預簽署POST 提供了便捷的方式方法。以下是如何在Go 中實現此目的:
1.配置儲存桶存取:
修改您的S3 儲存桶的策略以允許公開下載:
{ "Version": "2012-10-17", "Id": "akjsdhakshfjlashdf", "Statement": [ { "Sid": "kjahsdkajhsdkjasda", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::BUCKETNAMEHERE/*" } ] }
2.建立預簽POST策略:
制定授予上傳權限的 HTTP POST 策略:
{ "expiration": "%s", "conditions": [ {"bucket": "%s"}, ["starts-with", "$key", "%s"], {"acl": "public-read"}, {"x-amz-credential": "%s"}, {"x-amz-algorithm": "AWS4-HMAC-SHA256"}, {"x-amz-date": "%s" } ] }
使用下列參數設定策略:
憑證:您的AWS 憑證
憑證:您的AWS 憑證
使用Base64 對策略進行編碼
計算HMAC-SHA256 簽章
import "github.com/aws/aws-sdk-go/aws/credentials" type Field struct { Key, Value string } func Upload(url string, fields []Field) error { b := new(bytes.Buffer) w := multipart.NewWriter(b) for _, field := range fields { fw, err := w.CreateFormField(field.Key) if err != nil { return err } if _, err := fw.Write([]byte(field.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()) creds := &credentials.StaticProvider{Value: credentials.Value{ AccessKeyID: "AKIAIOSFODNN7EXAMPLE", SecretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", }} cfg := &aws.Config{Credentials: creds} client := new(&http.Client{Transport: &aws.HTTPSHandler{Client: *client, Config: *cfg}}) res, err := client.Do(req) if err != nil { return err } if res.StatusCode != http.StatusOK { return fmt.Errorf("bad status: %s", res.Status) } return nil }
以上是如何使用Go實作預簽POST檔上傳到AWS S3?的詳細內容。更多資訊請關注PHP中文網其他相關文章!