我需要在文件上传到S3后更新文件头。我无法控制上传过程(我使用的FilePicker.io API并没有提供一种方法来指定我现在的缓存控制标题),它们只是神奇地出现在一个桶里。我拥有对象的完整s3路径以及存储桶的密钥和秘密。
使用Go,向这些对象添加新标头的最简单方法是什么?似乎您需要执行PUT复制请求,但这需要请求签名并覆盖所有现有标头。我想要做的就是添加一个缓存控制头,必须有一个更简单的方法吗?
答案 0 :(得分:1)
下面的小程序应该只是将缓存控制标头添加到给定的存储桶/密钥组合中。重要的是s3.CopyOptions结构。 MetadataDirective也可以是COPY
- 有关详细信息,请参阅http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectCOPY.html。
此外,源必须是桶/密钥,因为源当然可以在另一个桶中。
package main
import (
"fmt"
"os"
"github.com/goamz/goamz/aws"
"github.com/goamz/goamz/s3"
//// should work as well
//"github.com/crowdmob/goamz/aws"
//"github.com/crowdmob/goamz/s3"
)
func main() {
// use as
// $ go run s3meta.go bucket key
// will add a 1 hour Cache-Control header to
// key in bucket
auth := aws.Auth{
AccessKey: os.Getenv("AWS_ACCESS_KEY_ID"),
SecretKey: os.Getenv("AWS_SECRET_KEY_ID"),
}
bucketName, keyName := os.Args[1], os.Args[2]
bucket := s3.New(auth, aws.USEast).Bucket(bucketName)
opts := s3.CopyOptions{}
opts.CacheControl = "maxage=3600"
opts.MetadataDirective = "REPLACE"
_, err := bucket.PutCopy(keyName, s3.PublicRead, opts, bucketName+"/"+keyName)
if err != nil {
panic(err)
}
}
试运行(桶已被删除):
╭─brs at stengaard in ~/ using
╰─○ curl -I https://s3.amazonaws.com/cf-templates-1r14by1vl75o0-us-east-1/success.png
HTTP/1.1 200 OK
x-amz-id-2: 49oTuRARMHlx32nqv34CMOjdTMBUCZIVzP8YKBS2Wz5h1w5KBG62u8nFru1UkIbJ
x-amz-request-id: C92E9952BFF31D77
Date: Mon, 30 Jun 2014 08:57:15 GMT
Last-Modified: Mon, 30 Jun 2014 08:50:45 GMT
ETag: "41b9951893f1bbff89e2b9c8a5b7ea18"
Accept-Ranges: bytes
Content-Type: image/png
Content-Length: 61585
Server: AmazonS3
╭─brs at stengaard in ~/ using
╰─○ go run s3meta.go cf-templates-1r14by1vl75o0-us-east-1 success.png
╭─brs at stengaard in ~/ using
╰─○ curl -I https://s3.amazonaws.com/cf-templates-1r14by1vl75o0-us-east-1/success.png
HTTP/1.1 200 OK
x-amz-id-2: oiDeXjO1V4kquWo8UlNWBi/HAHoqfvlOSHVeXFZXv2yA4o0+Njcdshhu15PIiw7J
x-amz-request-id: 0BB1A397DE7EBE75
Date: Mon, 30 Jun 2014 09:00:17 GMT
Cache-Control: maxage=3600
Last-Modified: Mon, 30 Jun 2014 09:00:12 GMT
ETag: "41b9951893f1bbff89e2b9c8a5b7ea18"
Accept-Ranges: bytes
Content-Type: binary/octet-stream
Content-Length: 61585
Server: AmazonS3
请注意,Content-Type也会更改,因为我们有opts.MetadataDirective = "REPLACE"
。如果这个小东西值得在带外更新标题的麻烦是真的特定于域:在客户端缓存上传的文件有多重要?向{1}}请求执行是否代价高昂?