minio-go: update to new version of minio-go

This change comes with wider re-structure inside minio-go and lots
of code cleanup.
This commit is contained in:
Harshavardhana
2015-11-09 23:03:45 -08:00
parent 3fca2428ad
commit 03e9fa70dd
15 changed files with 634 additions and 472 deletions
+1 -1
View File
@@ -34,7 +34,7 @@ import (
type s3Client struct {
mu *sync.Mutex
api minio.API
api minio.CloudStorageAPI
hostURL *client.URL
}
+74 -17
View File
@@ -1,12 +1,32 @@
# Minio Go Library for Amazon S3 Compatible Cloud Storage [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Description
Minio Go library is a simple client library for S3 compatible cloud storage servers. Supports AWS Signature Version 4 and 2. AWS Signature Version 4 is chosen as default.
List of supported cloud storage providers.
- AWS Signature Version 4
- Amazon S3
- Minio
- AWS Signature Version 2
- Openstack Swift + Swift3 middleware
- Ceph Object Gateway
- Riak CS
## Install
```sh
$ go get github.com/minio/minio-go
```
## Example
### ListBuckets() - AWS Signature Version 4.
This example shows how to List your buckets with default AWS Signature Version 4.
```go
package main
@@ -35,30 +55,67 @@ func main() {
}
```
### ListBuckets() - AWS Signature Version 2.
This example shows how to List your buckets with AWS Signature Version 2.
```go
package main
import (
"log"
"github.com/minio/minio-go"
)
func main() {
config := minio.Config{
AccessKeyID: "YOUR-ACCESS-KEY-HERE",
SecretAccessKey: "YOUR-PASSWORD-HERE",
Endpoint: "https://s3.amazonaws.com",
Signature: minio.SignatureV2,
}
s3Client, err := minio.New(config)
if err != nil {
log.Fatalln(err)
}
for bucket := range s3Client.ListBuckets() {
if bucket.Err != nil {
log.Fatalln(bucket.Err)
}
log.Println(bucket.Stat)
}
}
```
## Documentation
### Bucket Level
* [MakeBucket(bucket, acl) error](examples/s3/makebucket.go)
* [BucketExists(bucket) error](examples/s3/bucketexists.go)
* [RemoveBucket(bucket) error](examples/s3/removebucket.go)
* [GetBucketACL(bucket) (BucketACL, error)](examples/s3/getbucketacl.go)
* [SetBucketACL(bucket, BucketACL) error)](examples/s3/setbucketacl.go)
* [ListBuckets() <-chan BucketStat](examples/s3/listbuckets.go)
* [ListObjects(bucket, prefix, recursive) <-chan ObjectStat](examples/s3/listobjects.go)
* [ListIncompleteUploads(bucket, prefix, recursive) <-chan ObjectMultipartStat](examples/s3/listincompleteuploads.go)
* [MakeBucket(bucket, acl) error](examples/s3-v4/makebucket.go)
* [BucketExists(bucket) error](examples/s3-v4/bucketexists.go)
* [RemoveBucket(bucket) error](examples/s3-v4/removebucket.go)
* [GetBucketACL(bucket) (BucketACL, error)](examples/s3-v4/getbucketacl.go)
* [SetBucketACL(bucket, BucketACL) error)](examples/s3-v4/setbucketacl.go)
* [ListBuckets() <-chan BucketStat](examples/s3-v4/listbuckets.go)
* [ListObjects(bucket, prefix, recursive) <-chan ObjectStat](examples/s3-v4/listobjects.go)
* [ListIncompleteUploads(bucket, prefix, recursive) <-chan ObjectMultipartStat](examples/s3-v4/listincompleteuploads.go)
### Object Level
* [PutObject(bucket, object, size, io.Reader) error](examples/s3/putobject.go)
* [GetObject(bucket, object) (io.Reader, ObjectStat, error)](examples/s3/getobject.go)
* [GetPartialObject(bucket, object, offset, length) (io.Reader, ObjectStat, error)](examples/s3/getpartialobject.go)
* [StatObject(bucket, object) (ObjectStat, error)](examples/s3/statobject.go)
* [RemoveObject(bucket, object) error](examples/s3/removeobject.go)
* [RemoveIncompleteUpload(bucket, object) <-chan error](examples/s3/removeincompleteupload.go)
* [PutObject(bucket, object, size, io.Reader) error](examples/s3-v4/putobject.go)
* [GetObject(bucket, object) (io.Reader, ObjectStat, error)](examples/s3-v4/getobject.go)
* [GetPartialObject(bucket, object, offset, length) (io.Reader, ObjectStat, error)](examples/s3-v4/getpartialobject.go)
* [StatObject(bucket, object) (ObjectStat, error)](examples/s3-v4/statobject.go)
* [RemoveObject(bucket, object) error](examples/s3-v4/removeobject.go)
* [RemoveIncompleteUpload(bucket, object) <-chan error](examples/s3-v4/removeincompleteupload.go)
### Presigned Bucket/Object Level
* [PresignedGetObject(bucket, object, time.Duration) (string, error)](examples/s3/presignedgetobject.go)
* [PresignedPutObject(bucket, object, time.Duration) (string, error)](examples/s3/presignedputobject.go)
* [PresignedPostPolicy(NewPostPolicy()) (map[string]string, error)](examples/s3/presignedpostpolicy.go)
* [PresignedGetObject(bucket, object, time.Duration) (string, error)](examples/s3-v4/presignedgetobject.go)
* [PresignedPutObject(bucket, object, time.Duration) (string, error)](examples/s3-v4/presignedputobject.go)
* [PresignedPostPolicy(NewPostPolicy()) (map[string]string, error)](examples/s3-v4/presignedpostpolicy.go)
## Additional Documentation
More examples with AWS Signature Version 2 can be found [here](examples/s3-v2)
### API Reference
+90 -70
View File
@@ -33,21 +33,21 @@ const (
separator = "/"
)
// apiCore container to hold unexported internal functions
// apiCore container to hold unexported internal functions.
type apiCore struct {
config *Config
}
// closeResp close non nil response with any response Body
// closeResp close non nil response with any response Body.
func closeResp(resp *http.Response) {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
}
// putBucketRequest wrapper creates a new putBucket request
func (a apiCore) putBucketRequest(bucket, acl, location string) (*request, error) {
var r *request
// putBucketRequest wrapper creates a new putBucket request.
func (a apiCore) putBucketRequest(bucket, acl, location string) (*Request, error) {
var r *Request
var err error
op := &operation{
HTTPServer: a.config.Endpoint,
@@ -55,7 +55,7 @@ func (a apiCore) putBucketRequest(bucket, acl, location string) (*request, error
HTTPPath: separator + bucket,
}
var createBucketConfigBuffer *bytes.Reader
// If location is set use it and create proper bucket configuration
// If location is set use it and create proper bucket configuration.
switch {
case location != "":
createBucketConfig := new(createBucketConfiguration)
@@ -100,10 +100,10 @@ func (a apiCore) putBucketRequest(bucket, acl, location string) (*request, error
/// Bucket Write Operations
// putBucket create a new bucket
// putBucket create a new bucket.
//
// Requires valid AWS Access Key ID to authenticate requests
// Anonymous requests are never allowed to create buckets
// Requires valid AWS Access Key ID to authenticate requests.
// Anonymous requests are never allowed to create buckets.
//
// optional arguments are acl and location - by default all buckets are created
// with ``private`` acl and location set to US Standard if one wishes to set
@@ -111,16 +111,15 @@ func (a apiCore) putBucketRequest(bucket, acl, location string) (*request, error
//
// ACL valid values
// ------------------
// private - owner gets full access [DEFAULT]
// public-read - owner gets full access, others get read access
// public-read-write - owner gets full access, others get full access too
// authenticated-read - owner gets full access, authenticated users get read access
// private - owner gets full access [DEFAULT].
// public-read - owner gets full access, others get read access.
// public-read-write - owner gets full access, others get full access too.
// authenticated-read - owner gets full access, authenticated users get read access.
// ------------------
//
// Location valid values
// Location valid values.
// ------------------
// [ us-west-1 | us-west-2 | eu-west-1 | eu-central-1 | ap-southeast-1 | ap-northeast-1 | ap-southeast-2 | sa-east-1 ]
//
// Default - US standard
func (a apiCore) putBucket(bucket, acl, location string) error {
req, err := a.putBucketRequest(bucket, acl, location)
@@ -140,8 +139,8 @@ func (a apiCore) putBucket(bucket, acl, location string) error {
return nil
}
// putBucketRequestACL wrapper creates a new putBucketACL request
func (a apiCore) putBucketACLRequest(bucket, acl string) (*request, error) {
// putBucketRequestACL wrapper creates a new putBucketACL request.
func (a apiCore) putBucketACLRequest(bucket, acl string) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "PUT",
@@ -155,7 +154,7 @@ func (a apiCore) putBucketACLRequest(bucket, acl string) (*request, error) {
return req, nil
}
// putBucketACL set the permissions on an existing bucket using Canned ACL's
// putBucketACL set the permissions on an existing bucket using Canned ACL's.
func (a apiCore) putBucketACL(bucket, acl string) error {
req, err := a.putBucketACLRequest(bucket, acl)
if err != nil {
@@ -174,8 +173,8 @@ func (a apiCore) putBucketACL(bucket, acl string) error {
return nil
}
// getBucketACLRequest wrapper creates a new getBucketACL request
func (a apiCore) getBucketACLRequest(bucket string) (*request, error) {
// getBucketACLRequest wrapper creates a new getBucketACL request.
func (a apiCore) getBucketACLRequest(bucket string) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "GET",
@@ -188,7 +187,7 @@ func (a apiCore) getBucketACLRequest(bucket string) (*request, error) {
return req, nil
}
// getBucketACL get the acl information on an existing bucket
// getBucketACL get the acl information on an existing bucket.
func (a apiCore) getBucketACL(bucket string) (accessControlPolicy, error) {
req, err := a.getBucketACLRequest(bucket)
if err != nil {
@@ -209,7 +208,7 @@ func (a apiCore) getBucketACL(bucket string) (accessControlPolicy, error) {
if err != nil {
return accessControlPolicy{}, err
}
// In-case of google private bucket policy doesn't have any Grant list
// In-case of google private bucket policy doesn't have any Grant list.
if a.config.Region == "google" {
return policy, nil
}
@@ -226,8 +225,8 @@ func (a apiCore) getBucketACL(bucket string) (accessControlPolicy, error) {
return policy, nil
}
// getBucketLocationRequest wrapper creates a new getBucketLocation request
func (a apiCore) getBucketLocationRequest(bucket string) (*request, error) {
// getBucketLocationRequest wrapper creates a new getBucketLocation request.
func (a apiCore) getBucketLocationRequest(bucket string) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "GET",
@@ -240,7 +239,7 @@ func (a apiCore) getBucketLocationRequest(bucket string) (*request, error) {
return req, nil
}
// getBucketLocation uses location subresource to return a bucket's region
// getBucketLocation uses location subresource to return a bucket's region.
func (a apiCore) getBucketLocation(bucket string) (string, error) {
req, err := a.getBucketLocationRequest(bucket)
if err != nil {
@@ -264,9 +263,9 @@ func (a apiCore) getBucketLocation(bucket string) (string, error) {
return locationConstraint, nil
}
// listObjectsRequest wrapper creates a new listObjects request
func (a apiCore) listObjectsRequest(bucket, marker, prefix, delimiter string, maxkeys int) (*request, error) {
// resourceQuery - get resources properly escaped and lined up before using them in http request
// listObjectsRequest wrapper creates a new listObjects request.
func (a apiCore) listObjectsRequest(bucket, marker, prefix, delimiter string, maxkeys int) (*Request, error) {
// resourceQuery - get resources properly escaped and lined up before using them in http request.
resourceQuery := func() (*string, error) {
switch {
case marker != "":
@@ -297,7 +296,7 @@ func (a apiCore) listObjectsRequest(bucket, marker, prefix, delimiter string, ma
return r, nil
}
/// Bucket Read Operations
/// Bucket Read Operations.
// listObjects - (List Objects) - List some or all (up to 1000) of the objects in a bucket.
//
@@ -331,12 +330,12 @@ func (a apiCore) listObjects(bucket, marker, prefix, delimiter string, maxkeys i
if err != nil {
return listBucketResult, err
}
// close body while returning, along with any error
// close body while returning, along with any error.
return listBucketResult, nil
}
// headBucketRequest wrapper creates a new headBucket request
func (a apiCore) headBucketRequest(bucket string) (*request, error) {
// headBucketRequest wrapper creates a new headBucket request.
func (a apiCore) headBucketRequest(bucket string) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "HEAD",
@@ -361,7 +360,7 @@ func (a apiCore) headBucket(bucket string) error {
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
// Head has no response body, handle it
// Head has no response body, handle it.
var errorResponse ErrorResponse
switch resp.StatusCode {
case http.StatusNotFound:
@@ -395,8 +394,8 @@ func (a apiCore) headBucket(bucket string) error {
return nil
}
// deleteBucketRequest wrapper creates a new deleteBucket request
func (a apiCore) deleteBucketRequest(bucket string) (*request, error) {
// deleteBucketRequest wrapper creates a new deleteBucket request.
func (a apiCore) deleteBucketRequest(bucket string) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "DELETE",
@@ -405,11 +404,11 @@ func (a apiCore) deleteBucketRequest(bucket string) (*request, error) {
return newRequest(op, a.config, nil)
}
// deleteBucket deletes the bucket named in the URI
// deleteBucket deletes the bucket named in the URI.
//
// NOTE: -
// All objects (including all object versions and delete markers)
// in the bucket must be deleted before successfully attempting this request
// in the bucket must be deleted before successfully attempting this request.
func (a apiCore) deleteBucket(bucket string) error {
if err := invalidBucketError(bucket); err != nil {
return err
@@ -468,7 +467,9 @@ func (a apiCore) deleteBucket(bucket string) error {
/// Object Read/Write/Stat Operations
func (a apiCore) putObjectUnAuthenticatedRequest(bucket, object, contentType string, size int64, body io.Reader) (*request, error) {
// putObjectUnAuthenticatedRequest - putObjectUnauthenticated request.
func (a apiCore) putObjectUnAuthenticatedRequest(bucket, object, contentType string,
size int64, body io.Reader) (*Request, error) {
if strings.TrimSpace(contentType) == "" {
contentType = "application/octet-stream"
}
@@ -481,15 +482,16 @@ func (a apiCore) putObjectUnAuthenticatedRequest(bucket, object, contentType str
if err != nil {
return nil, err
}
// Content-MD5 is not set consciously
// Content-MD5 is not set, since its not calculated.
r.Set("Content-Type", contentType)
r.req.ContentLength = size
return r, nil
}
// putObjectUnAuthenticated - add an object to a bucket
// NOTE: You must have WRITE permissions on a bucket to add an object to it.
func (a apiCore) putObjectUnAuthenticated(bucket, object, contentType string, size int64, body io.Reader) (ObjectStat, error) {
// putObjectUnAuthenticated - add an object to a bucket anonymously.
// NOTE: You must have WRITE permissions on a bucket to add an object to it. Bucket should have 'public-read-write' ACL.
func (a apiCore) putObjectUnAuthenticated(bucket, object, contentType string,
size int64, body io.Reader) (ObjectStat, error) {
req, err := a.putObjectUnAuthenticatedRequest(bucket, object, contentType, size, body)
if err != nil {
return ObjectStat{}, err
@@ -509,8 +511,9 @@ func (a apiCore) putObjectUnAuthenticated(bucket, object, contentType string, si
return metadata, nil
}
// putObjectRequest wrapper creates a new PutObject request
func (a apiCore) putObjectRequest(bucket, object, contentType string, md5SumBytes []byte, size int64, body io.ReadSeeker) (*request, error) {
// putObjectRequest wrapper creates a new PutObject request.
func (a apiCore) putObjectRequest(bucket, object, contentType string,
md5SumBytes []byte, size int64, body io.ReadSeeker) (*Request, error) {
if strings.TrimSpace(contentType) == "" {
contentType = "application/octet-stream"
}
@@ -523,7 +526,7 @@ func (a apiCore) putObjectRequest(bucket, object, contentType string, md5SumByte
if err != nil {
return nil, err
}
// set Content-MD5 as base64 encoded md5
// set Content-MD5 as base64 encoded md5.
if md5SumBytes != nil {
r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes))
}
@@ -532,9 +535,10 @@ func (a apiCore) putObjectRequest(bucket, object, contentType string, md5SumByte
return r, nil
}
// putObject - add an object to a bucket
// putObject - add an object to a bucket.
// NOTE: You must have WRITE permissions on a bucket to add an object to it.
func (a apiCore) putObject(bucket, object, contentType string, md5SumBytes []byte, size int64, body io.ReadSeeker) (ObjectStat, error) {
func (a apiCore) putObject(bucket, object, contentType string,
md5SumBytes []byte, size int64, body io.ReadSeeker) (ObjectStat, error) {
req, err := a.putObjectRequest(bucket, object, contentType, md5SumBytes, size, body)
if err != nil {
return ObjectStat{}, err
@@ -554,9 +558,10 @@ func (a apiCore) putObject(bucket, object, contentType string, md5SumBytes []byt
return metadata, nil
}
// presignedPostPolicy - generate post form data.
func (a apiCore) presignedPostPolicy(p *PostPolicy) map[string]string {
t := time.Now().UTC()
r := new(request)
r := new(Request)
r.config = a.config
if r.config.Signature.isV2() {
policyBase64 := p.base64()
@@ -566,10 +571,21 @@ func (a apiCore) presignedPostPolicy(p *PostPolicy) map[string]string {
return p.formData
}
credential := getCredential(r.config.AccessKeyID, r.config.Region, t)
p.addNewPolicy(policy{"eq", "$x-amz-date", t.Format(iso8601DateFormat)})
p.addNewPolicy(policy{"eq", "$x-amz-algorithm", authHeader})
p.addNewPolicy(policy{"eq", "$x-amz-credential", credential})
p.addNewPolicy(policyCondition{
matchType: "eq",
condition: "$x-amz-date",
value: t.Format(iso8601DateFormat),
})
p.addNewPolicy(policyCondition{
matchType: "eq",
condition: "$x-amz-algorithm",
value: authHeader,
})
p.addNewPolicy(policyCondition{
matchType: "eq",
condition: "$x-amz-credential",
value: credential,
})
policyBase64 := p.base64()
p.formData["policy"] = policyBase64
p.formData["x-amz-algorithm"] = authHeader
@@ -579,6 +595,7 @@ func (a apiCore) presignedPostPolicy(p *PostPolicy) map[string]string {
return p.formData
}
// presignedPutObject - generate presigned PUT url.
func (a apiCore) presignedPutObject(bucket, object string, expires int64) (string, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
@@ -595,7 +612,8 @@ func (a apiCore) presignedPutObject(bucket, object string, expires int64) (strin
return r.PreSignV4()
}
func (a apiCore) presignedGetObjectRequest(bucket, object string, expires, offset, length int64) (*request, error) {
// presignedGetObjectRequest - presigned get object request
func (a apiCore) presignedGetObjectRequest(bucket, object string, expires, offset, length int64) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "GET",
@@ -616,6 +634,7 @@ func (a apiCore) presignedGetObjectRequest(bucket, object string, expires, offse
return r, nil
}
// presignedGetObject - generate presigned get object URL.
func (a apiCore) presignedGetObject(bucket, object string, expires, offset, length int64) (string, error) {
if err := invalidArgumentError(object); err != nil {
return "", err
@@ -630,8 +649,8 @@ func (a apiCore) presignedGetObject(bucket, object string, expires, offset, leng
return r.PreSignV4()
}
// getObjectRequest wrapper creates a new getObject request
func (a apiCore) getObjectRequest(bucket, object string, offset, length int64) (*request, error) {
// getObjectRequest wrapper creates a new getObject request.
func (a apiCore) getObjectRequest(bucket, object string, offset, length int64) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "GET",
@@ -642,17 +661,18 @@ func (a apiCore) getObjectRequest(bucket, object string, offset, length int64) (
return nil, err
}
switch {
case length > 0 && offset > 0:
case length > 0 && offset >= 0:
r.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1))
case offset > 0 && length == 0:
r.Set("Range", fmt.Sprintf("bytes=%d-", offset))
case length > 0 && offset == 0:
r.Set("Range", fmt.Sprintf("bytes=-%d", length))
// The final length bytes
case length < 0 && offset == 0:
r.Set("Range", fmt.Sprintf("bytes=%d", length))
}
return r, nil
}
// getObject - retrieve object from Object Storage
// getObject - retrieve object from Object Storage.
//
// Additionally this function also takes range arguments to download the specified
// range bytes of an object. Setting offset and length = 0 will download the full object.
@@ -704,8 +724,8 @@ func (a apiCore) getObject(bucket, object string, offset, length int64) (io.Read
return resp.Body, objectstat, nil
}
// deleteObjectRequest wrapper creates a new deleteObject request
func (a apiCore) deleteObjectRequest(bucket, object string) (*request, error) {
// deleteObjectRequest wrapper creates a new deleteObject request.
func (a apiCore) deleteObjectRequest(bucket, object string) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "DELETE",
@@ -714,7 +734,7 @@ func (a apiCore) deleteObjectRequest(bucket, object string) (*request, error) {
return newRequest(op, a.config, nil)
}
// deleteObject deletes a given object from a bucket
// deleteObject deletes a given object from a bucket.
func (a apiCore) deleteObject(bucket, object string) error {
if err := invalidBucketError(bucket); err != nil {
return err
@@ -766,8 +786,8 @@ func (a apiCore) deleteObject(bucket, object string) error {
return nil
}
// headObjectRequest wrapper creates a new headObject request
func (a apiCore) headObjectRequest(bucket, object string) (*request, error) {
// headObjectRequest wrapper creates a new headObject request.
func (a apiCore) headObjectRequest(bucket, object string) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "HEAD",
@@ -776,7 +796,7 @@ func (a apiCore) headObjectRequest(bucket, object string) (*request, error) {
return newRequest(op, a.config, nil)
}
// headObject retrieves metadata from an object without returning the object itself
// headObject retrieves metadata from an object without returning the object itself.
func (a apiCore) headObject(bucket, object string) (ObjectStat, error) {
if err := invalidBucketError(bucket); err != nil {
return ObjectStat{}, err
@@ -859,10 +879,10 @@ func (a apiCore) headObject(bucket, object string) (ObjectStat, error) {
return objectstat, nil
}
/// Service Operations
/// Service Operations.
// listBucketRequest wrapper creates a new listBuckets request
func (a apiCore) listBucketsRequest() (*request, error) {
// listBucketRequest wrapper creates a new listBuckets request.
func (a apiCore) listBucketsRequest() (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "GET",
@@ -871,7 +891,7 @@ func (a apiCore) listBucketsRequest() (*request, error) {
return newRequest(op, a.config, nil)
}
// listBuckets list of all buckets owned by the authenticated sender of the request
// listBuckets list of all buckets owned by the authenticated sender of the request.
func (a apiCore) listBuckets() (listAllMyBucketsResult, error) {
req, err := a.listBucketsRequest()
if err != nil {
@@ -883,7 +903,7 @@ func (a apiCore) listBuckets() (listAllMyBucketsResult, error) {
return listAllMyBucketsResult{}, err
}
if resp != nil {
// for un-authenticated requests, amazon sends a redirect handle it
// for un-authenticated requests, amazon sends a redirect handle it.
if resp.StatusCode == http.StatusTemporaryRedirect {
return listAllMyBucketsResult{}, ErrorResponse{
Code: "AccessDenied",
+32 -27
View File
@@ -28,9 +28,9 @@ import (
"strconv"
)
// listMultipartUploadsRequest wrapper creates a new listMultipartUploads request
func (a apiCore) listMultipartUploadsRequest(bucket, keymarker, uploadIDMarker, prefix, delimiter string, maxuploads int) (*request, error) {
// resourceQuery - get resources properly escaped and lined up before using them in http request
// listMultipartUploadsRequest wrapper creates a new listMultipartUploads request.
func (a apiCore) listMultipartUploadsRequest(bucket, keymarker, uploadIDMarker, prefix, delimiter string, maxuploads int) (*Request, error) {
// resourceQuery get resources properly escaped and lined up before using them in http request.
resourceQuery := func() (string, error) {
switch {
case keymarker != "":
@@ -64,13 +64,14 @@ func (a apiCore) listMultipartUploadsRequest(bucket, keymarker, uploadIDMarker,
return r, nil
}
// listMultipartUploads - (List Multipart Uploads) - Lists some or all (up to 1000) in-progress multipart uploads in a bucket.
// listMultipartUploads - (List Multipart Uploads).
// - Lists some or all (up to 1000) in-progress multipart uploads in a bucket.
//
// You can use the request parameters as selection criteria to return a subset of the uploads in a bucket.
// request paramters :-
// request paramters. :-
// ---------
// ?key-marker - Specifies the multipart upload after which listing should begin
// ?upload-id-marker - Together with key-marker specifies the multipart upload after which listing should begin
// ?key-marker - Specifies the multipart upload after which listing should begin.
// ?upload-id-marker - Together with key-marker specifies the multipart upload after which listing should begin.
// ?delimiter - A delimiter is a character you use to group keys.
// ?prefix - Limits the response to keys that begin with the specified prefix.
// ?max-uploads - Sets the maximum number of multipart uploads returned in the response body.
@@ -94,12 +95,12 @@ func (a apiCore) listMultipartUploads(bucket, keymarker, uploadIDMarker, prefix,
if err != nil {
return listMultipartUploadsResult, err
}
// close body while returning, along with any error
// close body while returning, along with any error.
return listMultipartUploadsResult, nil
}
// initiateMultipartRequest wrapper creates a new initiateMultiPart request
func (a apiCore) initiateMultipartRequest(bucket, object string) (*request, error) {
// initiateMultipartRequest wrapper creates a new initiateMultiPart request.
func (a apiCore) initiateMultipartRequest(bucket, object string) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "POST",
@@ -108,7 +109,7 @@ func (a apiCore) initiateMultipartRequest(bucket, object string) (*request, erro
return newRequest(op, a.config, nil)
}
// initiateMultipartUpload initiates a multipart upload and returns an upload ID
// initiateMultipartUpload initiates a multipart upload and returns an upload ID.
func (a apiCore) initiateMultipartUpload(bucket, object string) (initiateMultipartUploadResult, error) {
req, err := a.initiateMultipartRequest(bucket, object)
if err != nil {
@@ -132,8 +133,8 @@ func (a apiCore) initiateMultipartUpload(bucket, object string) (initiateMultipa
return initiateMultipartUploadResult, nil
}
// completeMultipartUploadRequest wrapper creates a new CompleteMultipartUpload request
func (a apiCore) completeMultipartUploadRequest(bucket, object, uploadID string, complete completeMultipartUpload) (*request, error) {
// completeMultipartUploadRequest wrapper creates a new CompleteMultipartUpload request.
func (a apiCore) completeMultipartUploadRequest(bucket, object, uploadID string, complete completeMultipartUpload) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "POST",
@@ -185,8 +186,8 @@ func (a apiCore) completeMultipartUpload(bucket, object, uploadID string, c comp
return completeMultipartUploadResult, nil
}
// abortMultipartUploadRequest wrapper creates a new AbortMultipartUpload request
func (a apiCore) abortMultipartUploadRequest(bucket, object, uploadID string) (*request, error) {
// abortMultipartUploadRequest wrapper creates a new AbortMultipartUpload request.
func (a apiCore) abortMultipartUploadRequest(bucket, object, uploadID string) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "DELETE",
@@ -195,7 +196,7 @@ func (a apiCore) abortMultipartUploadRequest(bucket, object, uploadID string) (*
return newRequest(op, a.config, nil)
}
// abortMultipartUpload aborts a multipart upload for the given uploadID, all parts are deleted
// abortMultipartUpload aborts a multipart upload for the given uploadID, all parts are deleted.
func (a apiCore) abortMultipartUpload(bucket, object, uploadID string) error {
req, err := a.abortMultipartUploadRequest(bucket, object, uploadID)
if err != nil {
@@ -208,7 +209,7 @@ func (a apiCore) abortMultipartUpload(bucket, object, uploadID string) error {
}
if resp != nil {
if resp.StatusCode != http.StatusNoContent {
// Abort has no response body, handle it
// Abort has no response body, handle it.
var errorResponse ErrorResponse
switch resp.StatusCode {
case http.StatusNotFound:
@@ -239,9 +240,9 @@ func (a apiCore) abortMultipartUpload(bucket, object, uploadID string) error {
return nil
}
// listObjectPartsRequest wrapper creates a new ListObjectParts request
func (a apiCore) listObjectPartsRequest(bucket, object, uploadID string, partNumberMarker, maxParts int) (*request, error) {
// resourceQuery - get resources properly escaped and lined up before using them in http request
// listObjectPartsRequest wrapper creates a new ListObjectParts request.
func (a apiCore) listObjectPartsRequest(bucket, object, uploadID string, partNumberMarker, maxParts int) (*Request, error) {
// resourceQuery - get resources properly escaped and lined up before using them in http request.
resourceQuery := func() string {
var partNumberMarkerStr string
switch {
@@ -258,7 +259,8 @@ func (a apiCore) listObjectPartsRequest(bucket, object, uploadID string, partNum
return newRequest(op, a.config, nil)
}
// listObjectParts (List Parts) - lists some or all (up to 1000) parts that have been uploaded for a specific multipart upload
// listObjectParts (List Parts)
// - lists some or all (up to 1000) parts that have been uploaded for a specific multipart upload
//
// You can use the request parameters as selection criteria to return a subset of the uploads in a bucket.
// request paramters :-
@@ -287,18 +289,20 @@ func (a apiCore) listObjectParts(bucket, object, uploadID string, partNumberMark
return listObjectPartsResult, nil
}
// uploadPartRequest wrapper creates a new UploadPart request
func (a apiCore) uploadPartRequest(bucket, object, uploadID string, md5SumBytes []byte, partNumber int, size int64, body io.ReadSeeker) (*request, error) {
// uploadPartRequest wrapper creates a new UploadPart request.
func (a apiCore) uploadPartRequest(bucket, object, uploadID string,
md5SumBytes []byte, partNumber int, size int64, body io.ReadSeeker) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "PUT",
HTTPPath: separator + bucket + separator + object + "?partNumber=" + strconv.Itoa(partNumber) + "&uploadId=" + uploadID,
HTTPPath: separator + bucket + separator + object +
"?partNumber=" + strconv.Itoa(partNumber) + "&uploadId=" + uploadID,
}
r, err := newRequest(op, a.config, body)
if err != nil {
return nil, err
}
// set Content-MD5 as base64 encoded md5
// set Content-MD5 as base64 encoded md5.
if md5SumBytes != nil {
r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes))
}
@@ -307,7 +311,8 @@ func (a apiCore) uploadPartRequest(bucket, object, uploadID string, md5SumBytes
}
// uploadPart uploads a part in a multipart upload.
func (a apiCore) uploadPart(bucket, object, uploadID string, md5SumBytes []byte, partNumber int, size int64, body io.ReadSeeker) (completePart, error) {
func (a apiCore) uploadPart(bucket, object, uploadID string,
md5SumBytes []byte, partNumber int, size int64, body io.ReadSeeker) (completePart, error) {
req, err := a.uploadPartRequest(bucket, object, uploadID, md5SumBytes, partNumber, size, body)
if err != nil {
return completePart{}, err
@@ -316,7 +321,7 @@ func (a apiCore) uploadPart(bucket, object, uploadID string, md5SumBytes []byte,
cPart.PartNumber = partNumber
cPart.ETag = "\"" + hex.EncodeToString(md5SumBytes) + "\""
// initiate the request
// initiate the request.
resp, err := req.Do()
defer closeResp(resp)
if err != nil {
+175 -221
View File
@@ -31,68 +31,25 @@ import (
"time"
)
// API - Cloud Storage API interface
type API interface {
// Bucket Read/Write/Stat operations
BucketAPI
// Object Read/Write/Stat operations
ObjectAPI
// Presigned API
PresignedAPI
}
// BucketAPI - bucket specific Read/Write/Stat interface
type BucketAPI interface {
MakeBucket(bucket string, cannedACL BucketACL) error
BucketExists(bucket string) error
RemoveBucket(bucket string) error
SetBucketACL(bucket string, cannedACL BucketACL) error
GetBucketACL(bucket string) (BucketACL, error)
ListBuckets() <-chan BucketStatCh
ListObjects(bucket, prefix string, recursive bool) <-chan ObjectStatCh
ListIncompleteUploads(bucket, prefix string, recursive bool) <-chan ObjectMultipartStatCh
}
// ObjectAPI - object specific Read/Write/Stat interface
type ObjectAPI interface {
GetObject(bucket, object string) (io.ReadCloser, ObjectStat, error)
GetPartialObject(bucket, object string, offset, length int64) (io.ReadCloser, ObjectStat, error)
PutObject(bucket, object, contentType string, size int64, data io.Reader) error
StatObject(bucket, object string) (ObjectStat, error)
RemoveObject(bucket, object string) error
RemoveIncompleteUpload(bucket, object string) <-chan error
}
// PresignedAPI - object specific for now
type PresignedAPI interface {
PresignedGetObject(bucket, object string, expires time.Duration) (string, error)
PresignedPutObject(bucket, object string, expires time.Duration) (string, error)
PresignedPostPolicy(*PostPolicy) (map[string]string, error)
}
// BucketStatCh - bucket metadata over read channel
// BucketStatCh - bucket metadata struct sent over read channel.
type BucketStatCh struct {
Stat BucketStat
Err error
}
// ObjectStatCh - object metadata over read channel
// ObjectStatCh - object metadata struct sent over read channel.
type ObjectStatCh struct {
Stat ObjectStat
Err error
}
// ObjectMultipartStatCh - multipart object metadata over read channel
// ObjectMultipartStatCh - multipart object metadata struct sent over read channel.
type ObjectMultipartStatCh struct {
Stat ObjectMultipartStat
Err error
}
// BucketStat container for bucket metadata
// BucketStat container for bucket metadata.
type BucketStat struct {
// The name of the bucket.
Name string
@@ -100,7 +57,7 @@ type BucketStat struct {
CreationDate time.Time
}
// ObjectStat container for object metadata
// ObjectStat container for object metadata.
type ObjectStat struct {
ETag string
Key string
@@ -117,7 +74,7 @@ type ObjectStat struct {
StorageClass string
}
// ObjectMultipartStat container for multipart object metadata
// ObjectMultipartStat container for multipart object metadata.
type ObjectMultipartStat struct {
// Date and time at which the multipart upload was initiated.
Initiated time.Time `type:"timestamp" timestampFormat:"iso8601"`
@@ -135,7 +92,7 @@ type ObjectMultipartStat struct {
UploadID string `xml:"UploadId"`
}
// Regions s3 region map used by bucket location constraint
// s3 region map used by bucket location constraint if necessary.
var regions = map[string]string{
"s3-fips-us-gov-west-1.amazonaws.com": "us-gov-west-1",
"s3.amazonaws.com": "us-east-1",
@@ -159,15 +116,15 @@ func getRegion(host string) (region string) {
if _, ok := regions[host]; ok {
return regions[host]
}
// Region cannot be empty according to Amazon S3.
// So we address all the four quadrants of our galaxy.
// Region cannot be empty according to Amazon S3 for AWS Signature Version 4.
// So we will in-turn address all the four quadrants of our galaxy.
return "milkyway"
}
// SignatureType is type of signature to be used for a request
// SignatureType is type of Authorization requested for a given HTTP request.
type SignatureType int
// Different types of supported signatures - default is Latest i.e SignatureV4
// Different types of supported signatures - default is Latest i.e SignatureV4.
const (
Latest SignatureType = iota
SignatureV4
@@ -189,29 +146,29 @@ func (s SignatureType) isLatest() bool {
return s == Latest
}
// Config - main configuration struct used by all to set endpoint, credentials, and other options for requests.
// Config - main configuration struct used to set endpoint, credentials, and other options for requests.
type Config struct {
// Standard options
AccessKeyID string
SecretAccessKey string
Endpoint string
Signature SignatureType
/// Standard options
AccessKeyID string // AccessKeyID required for authorized requests.
SecretAccessKey string // SecretAccessKey required for authorized requests.
Endpoint string // host endpoint eg:- https://s3.amazonaws.com
Signature SignatureType // choose a signature type if necessary.
// Advanced options
/// Advanced options
// Optional field. If empty, region is determined automatically.
// Set to override default behavior.
Region string
// Specify this to get server response in non XML style if server supports it
AcceptType string
// Optional field. If empty, region is determined automatically.
Region string
// Expert options
/// Really Advanced options
//
// Set this to override default transport ``http.DefaultTransport``
//
// This transport is usually needed for debugging OR to add your own
// custom TLS certificates on the client transport, for custom CA's and
// certs which are not part of standard certificate authority
//
// For example :-
// certs which are not part of standard certificate authority follow this
// example:-
//
// tr := &http.Transport{
// TLSClientConfig: &tls.Config{RootCAs: pool},
@@ -220,7 +177,7 @@ type Config struct {
//
Transport http.RoundTripper
// internal
/// Internal options
// use SetUserAgent append to default, useful when minio-go is used with in your application
userAgent string
isUserAgentSet bool // allow user agent's to be set only once
@@ -246,16 +203,17 @@ func (c *Config) SetUserAgent(name string, version string, comments ...string) {
}
}
type api struct {
// API is a container which delegates methods that comply with CloudStorageAPI interface.
type API struct {
apiCore
}
// New - instantiate a new minio api client
func New(config Config) (API, error) {
// New - instantiate minio client API with your input Config{}.
func New(config Config) (CloudStorageAPI, error) {
if strings.TrimSpace(config.Region) == "" || len(config.Region) == 0 {
u, err := url.Parse(config.Endpoint)
if err != nil {
return api{}, err
return API{}, err
}
match, _ := filepath.Match("*.s3*.amazonaws.com", u.Host)
if match {
@@ -277,11 +235,11 @@ func New(config Config) (API, error) {
}
config.SetUserAgent(LibraryName, LibraryVersion, runtime.GOOS, runtime.GOARCH)
config.isUserAgentSet = false // default
return api{apiCore{&config}}, nil
return API{apiCore{&config}}, nil
}
// PresignedPostPolicy return POST form data that can be used for object upload
func (a api) PresignedPostPolicy(p *PostPolicy) (map[string]string, error) {
// PresignedPostPolicy return POST form data that can be used for object upload.
func (a API) PresignedPostPolicy(p *PostPolicy) (map[string]string, error) {
if p.expiration.IsZero() {
return nil, errors.New("Expiration time must be specified")
}
@@ -294,12 +252,12 @@ func (a api) PresignedPostPolicy(p *PostPolicy) (map[string]string, error) {
return a.presignedPostPolicy(p), nil
}
/// Object operations
/// Object operations.
/// Expires maximum is 7days - ie. 604800 and minimum is 1
/// Expires maximum is 7days - ie. 604800 and minimum is 1.
// PresignedPutObject get a presigned URL to upload an object
func (a api) PresignedPutObject(bucket, object string, expires time.Duration) (string, error) {
// PresignedPutObject get a presigned URL to upload an object.
func (a API) PresignedPutObject(bucket, object string, expires time.Duration) (string, error) {
expireSeconds := int64(expires / time.Second)
if expireSeconds < 1 || expireSeconds > 604800 {
return "", invalidArgumentError("")
@@ -307,8 +265,8 @@ func (a api) PresignedPutObject(bucket, object string, expires time.Duration) (s
return a.presignedPutObject(bucket, object, expireSeconds)
}
// PresignedGetObject get a presigned URL to retrieve an object for third party apps
func (a api) PresignedGetObject(bucket, object string, expires time.Duration) (string, error) {
// PresignedGetObject get a presigned URL to retrieve an object for third party apps.
func (a API) PresignedGetObject(bucket, object string, expires time.Duration) (string, error) {
expireSeconds := int64(expires / time.Second)
if expireSeconds < 1 || expireSeconds > 604800 {
return "", invalidArgumentError("")
@@ -316,10 +274,8 @@ func (a api) PresignedGetObject(bucket, object string, expires time.Duration) (s
return a.presignedGetObject(bucket, object, expireSeconds, 0, 0)
}
// GetObject retrieve object
// Downloads full object with no ranges, if you need ranges use GetPartialObject
func (a api) GetObject(bucket, object string) (io.ReadCloser, ObjectStat, error) {
// GetObject retrieve object. retrieves full object, if you need ranges use GetPartialObject.
func (a API) GetObject(bucket, object string) (io.ReadCloser, ObjectStat, error) {
if err := invalidBucketError(bucket); err != nil {
return nil, ObjectStat{}, err
}
@@ -330,58 +286,58 @@ func (a api) GetObject(bucket, object string) (io.ReadCloser, ObjectStat, error)
return a.getObject(bucket, object, 0, 0)
}
// GetPartialObject retrieve partial object
// GetPartialObject retrieve partial object.
//
// Takes range arguments to download the specified range bytes of an object.
// Setting offset and length = 0 will download the full object.
// For more information about the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.
func (a api) GetPartialObject(bucket, object string, offset, length int64) (io.ReadCloser, ObjectStat, error) {
func (a API) GetPartialObject(bucket, object string, offset, length int64) (io.ReadCloser, ObjectStat, error) {
if err := invalidBucketError(bucket); err != nil {
return nil, ObjectStat{}, err
}
if err := invalidObjectError(object); err != nil {
return nil, ObjectStat{}, err
}
// get partial object
// get partial object.
return a.getObject(bucket, object, offset, length)
}
// completedParts is a wrapper to make parts sortable by their part number
// multi part completion requires list of multi parts to be sorted
// completedParts is a wrapper to make parts sortable by their part numbers.
// multi part completion requires list of multi parts to be sorted.
type completedParts []completePart
func (a completedParts) Len() int { return len(a) }
func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].PartNumber }
// minimumPartSize minimum part size per object after which PutObject behaves internally as multipart
// minimumPartSize minimum part size per object after which PutObject behaves internally as multipart.
var minimumPartSize int64 = 1024 * 1024 * 5
// maxParts - unexported right now
// maxParts - maximum parts for a single multipart session.
var maxParts = int64(10000)
// maxPartSize - unexported right now
// maxPartSize - maximum part size for a single multipart upload operation.
var maxPartSize int64 = 1024 * 1024 * 1024 * 5
// maxConcurrentQueue - max concurrent upload queue
// maxConcurrentQueue - max concurrent upload queue.
var maxConcurrentQueue int64 = 4
// calculatePartSize - calculate the optimal part size for the given objectSize
// calculatePartSize - calculate the optimal part size for the given objectSize.
//
// NOTE: Assumption here is that for any given object upload to a S3 compatible object
// storage it will have the following parameters as constants
// storage it will have the following parameters as constants.
//
// maxParts
// maximumPartSize
// minimumPartSize
//
// if a the partSize after division with maxParts is greater than minimumPartSize
// then choose that to be the new part size, if not return MinimumPartSize
// if the partSize after division with maxParts is greater than minimumPartSize
// then choose miniumPartSize as the new part size, if not return minimumPartSize.
//
// special case where it happens to be that partSize is indeed bigger than the
// maximum part size just return maxPartSize back
// maximum part size just return maxPartSize.
func calculatePartSize(objectSize int64) int64 {
// make sure last part has enough buffer and handle this poperly
// make sure last part has enough buffer and handle this poperly.
partSize := (objectSize / (maxParts - 1))
if partSize > minimumPartSize {
if partSize > maxPartSize {
@@ -392,7 +348,8 @@ func calculatePartSize(objectSize int64) int64 {
return minimumPartSize
}
func (a api) newObjectUpload(bucket, object, contentType string, size int64, data io.Reader) error {
// Initiate a fresh multipart upload
func (a API) newObjectUpload(bucket, object, contentType string, size int64, data io.Reader) error {
initMultipartUploadResult, err := a.initiateMultipartUpload(bucket, object)
if err != nil {
return err
@@ -401,11 +358,11 @@ func (a api) newObjectUpload(bucket, object, contentType string, size int64, dat
complMultipartUpload := completeMultipartUpload{}
var totalLength int64
// Calculate optimal part size for a given size
// Calculate optimal part size for a given size.
partSize := calculatePartSize(size)
// Allocate bufferred error channel for maximum parts
// Allocate bufferred error channel for maximum parts.
errCh := make(chan error, maxParts)
// Limit multi part queue size to concurrent
// Limit multi part queue size to concurrent.
mpQueueCh := make(chan struct{}, maxConcurrentQueue)
defer close(errCh)
defer close(mpQueueCh)
@@ -413,8 +370,8 @@ func (a api) newObjectUpload(bucket, object, contentType string, size int64, dat
wg := new(sync.WaitGroup)
for p := range chopper(data, partSize, nil) {
// This check is primarily for last part
// This verifies if the part.Len was an unexpected read i.e if we lost few bytes
// This check is primarily for last part.
// This verifies if the part.Len was an unexpected read i.e if we lost few bytes.
if p.Len < partSize && size > 0 {
expectedPartLen := size - totalLength
if expectedPartLen != p.Len {
@@ -425,11 +382,11 @@ func (a api) newObjectUpload(bucket, object, contentType string, size int64, dat
}
}
}
// Limit to 4 parts a given time
// Limit to 4 parts a given time.
mpQueueCh <- struct{}{}
// Account for all parts uploaded simultaneousy
// Account for all parts uploaded simultaneousy.
wg.Add(1)
go func(errCh chan<- error, mpQueueCh <-chan struct{}, p part) {
go func(errCh chan<- error, mpQueueCh <-chan struct{}, p piece) {
defer wg.Done()
defer func() {
<-mpQueueCh
@@ -461,29 +418,30 @@ func (a api) newObjectUpload(bucket, object, contentType string, size int64, dat
return nil
}
type partCh struct {
// partMetadatCh - individual part metadata struct over read channel
type partMetadataCh struct {
Metadata partMetadata
Err error
}
func (a api) listObjectPartsRecursive(bucket, object, uploadID string) <-chan partCh {
partCh := make(chan partCh, 1000)
func (a API) listObjectPartsRecursive(bucket, object, uploadID string) <-chan partMetadataCh {
partCh := make(chan partMetadataCh, 1000)
go a.listObjectPartsRecursiveInRoutine(bucket, object, uploadID, partCh)
return partCh
}
func (a api) listObjectPartsRecursiveInRoutine(bucket, object, uploadID string, ch chan partCh) {
func (a API) listObjectPartsRecursiveInRoutine(bucket, object, uploadID string, ch chan<- partMetadataCh) {
defer close(ch)
listObjPartsResult, err := a.listObjectParts(bucket, object, uploadID, 0, 1000)
if err != nil {
ch <- partCh{
ch <- partMetadataCh{
Metadata: partMetadata{},
Err: err,
}
return
}
for _, uploadedPart := range listObjPartsResult.Parts {
ch <- partCh{
ch <- partMetadataCh{
Metadata: uploadedPart,
Err: nil,
}
@@ -492,16 +450,17 @@ func (a api) listObjectPartsRecursiveInRoutine(bucket, object, uploadID string,
if !listObjPartsResult.IsTruncated {
break
}
listObjPartsResult, err = a.listObjectParts(bucket, object, uploadID, listObjPartsResult.NextPartNumberMarker, 1000)
listObjPartsResult, err = a.listObjectParts(bucket, object,
uploadID, listObjPartsResult.NextPartNumberMarker, 1000)
if err != nil {
ch <- partCh{
ch <- partMetadataCh{
Metadata: partMetadata{},
Err: err,
}
return
}
for _, uploadedPart := range listObjPartsResult.Parts {
ch <- partCh{
ch <- partMetadataCh{
Metadata: uploadedPart,
Err: nil,
}
@@ -509,7 +468,8 @@ func (a api) listObjectPartsRecursiveInRoutine(bucket, object, uploadID string,
}
}
func (a api) getMultipartSize(bucket, object, uploadID string) (int64, error) {
// getTotalMultipartSize - calculate total uploaded size for the a given multipart object.
func (a API) getTotalMultipartSize(bucket, object, uploadID string) (int64, error) {
var size int64
for part := range a.listObjectPartsRecursive(bucket, object, uploadID) {
if part.Err != nil {
@@ -520,8 +480,9 @@ func (a api) getMultipartSize(bucket, object, uploadID string) (int64, error) {
return size, nil
}
func (a api) continueObjectUpload(bucket, object, uploadID string, size int64, data io.Reader) error {
var skipParts []skipPart
// continue previously interrupted multipart upload object at `uploadID`
func (a API) continueObjectUpload(bucket, object, uploadID string, size int64, data io.Reader) error {
var skipPieces []skipPiece
completeMultipartUpload := completeMultipartUpload{}
var totalLength int64
for part := range a.listObjectPartsRecursive(bucket, object, uploadID) {
@@ -537,26 +498,26 @@ func (a api) continueObjectUpload(bucket, object, uploadID string, size int64, d
return err
}
totalLength += part.Metadata.Size
skipParts = append(skipParts, skipPart{
md5sum: md5SumBytes,
partNumber: part.Metadata.PartNumber,
skipPieces = append(skipPieces, skipPiece{
md5sum: md5SumBytes,
pieceNumber: part.Metadata.PartNumber,
})
}
// Calculate the optimal part size for a given size
// Calculate the optimal part size for a given size.
partSize := calculatePartSize(size)
// Allocate bufferred error channel for maximum parts
// Allocate bufferred error channel for maximum parts.
errCh := make(chan error, maxParts)
// Limit multipart queue size to concurrent
// Limit multipart queue size to maxConcurrentQueue.
mpQueueCh := make(chan struct{}, maxConcurrentQueue)
defer close(errCh)
defer close(mpQueueCh)
// Allocate a new wait group
// Allocate a new wait group.
wg := new(sync.WaitGroup)
for p := range chopper(data, partSize, skipParts) {
// This check is primarily for last part
// This verifies if the part.Len was an unexpected read i.e if we lost few bytes
for p := range chopper(data, partSize, skipPieces) {
// This check is primarily for last part.
// This verifies if the part.Len was an unexpected read i.e if we lost few bytes.
if p.Len < partSize && size > 0 {
expectedPartLen := size - totalLength
if expectedPartLen != p.Len {
@@ -567,11 +528,11 @@ func (a api) continueObjectUpload(bucket, object, uploadID string, size int64, d
}
}
}
// Limit to 4 parts a given time
// Limit to 4 parts a given time.
mpQueueCh <- struct{}{}
// Account for all parts uploaded simultaneousy
// Account for all parts uploaded simultaneousy.
wg.Add(1)
go func(errCh chan<- error, mpQueueCh <-chan struct{}, p part) {
go func(errCh chan<- error, mpQueueCh <-chan struct{}, p piece) {
defer wg.Done()
defer func() {
<-mpQueueCh
@@ -602,22 +563,22 @@ func (a api) continueObjectUpload(bucket, object, uploadID string, size int64, d
return nil
}
// PutObject create an object in a bucket
// PutObject create an object in a bucket.
//
// You must have WRITE permissions on a bucket to create an object
// You must have WRITE permissions on a bucket to create an object.
//
// This version of PutObject automatically does multipart for more than 5MB worth of data
func (a api) PutObject(bucket, object, contentType string, size int64, data io.Reader) error {
// This version of PutObject automatically does multipart for more than 5MB worth of data.
func (a API) PutObject(bucket, object, contentType string, size int64, data io.Reader) error {
if err := invalidBucketError(bucket); err != nil {
return err
}
if err := invalidArgumentError(object); err != nil {
return err
}
// for un-authenticated requests do not initiated multipart operation
// for un-authenticated requests do not initiated multipart operation.
//
// NOTE: this behavior is only kept valid for S3, since S3 doesn't
// allow unauthenticated multipart requests
// allow unauthenticated multipart requests.
if a.config.Region != "milkyway" {
if a.config.AccessKeyID == "" || a.config.SecretAccessKey == "" {
_, err := a.putObjectUnAuthenticated(bucket, object, contentType, size, data)
@@ -637,14 +598,14 @@ func (a api) PutObject(bucket, object, contentType string, size int64, data io.R
Resource: separator + bucket + separator + object,
}
}
if _, err := a.putObject(bucket, object, contentType, nil, size, ReadSeekCloser(data)); err != nil {
if _, err := a.putObject(bucket, object, contentType, nil, size, NewReadSeekCloser(data)); err != nil {
return err
}
return nil
}
switch {
case size < minimumPartSize && size > 0:
// Single Part use case, use PutObject directly
// Single Part use case, use PutObject directly.
for part := range chopper(data, minimumPartSize, nil) {
if part.Err != nil {
return part.Err
@@ -684,8 +645,8 @@ func (a api) PutObject(bucket, object, contentType string, size int64, data io.R
return errors.New("Unexpected control flow, please report this error at https://github.com/minio/minio-go/issues")
}
// StatObject verify if object exists and you have permission to access it
func (a api) StatObject(bucket, object string) (ObjectStat, error) {
// StatObject verify if object exists and you have permission to access it.
func (a API) StatObject(bucket, object string) (ObjectStat, error) {
if err := invalidBucketError(bucket); err != nil {
return ObjectStat{}, err
}
@@ -695,8 +656,8 @@ func (a api) StatObject(bucket, object string) (ObjectStat, error) {
return a.headObject(bucket, object)
}
// RemoveObject remove the object from a bucket
func (a api) RemoveObject(bucket, object string) error {
// RemoveObject remove an object from a bucket.
func (a API) RemoveObject(bucket, object string) error {
if err := invalidBucketError(bucket); err != nil {
return err
}
@@ -708,24 +669,19 @@ func (a api) RemoveObject(bucket, object string) error {
/// Bucket operations
// MakeBucket make a new bucket
// MakeBucket makes a new bucket.
//
// optional arguments are acl and location - by default all buckets are created
// with ``private`` acl and location set to US Standard if one wishes to set
// different ACLs and Location one can set them properly.
// Optional arguments are acl - by default all buckets are created
// with ``private`` acl.
//
// ACL valid values
//
// private - owner gets full access [default]
// public-read - owner gets full access, all others get read access
// public-read-write - owner gets full access, all others get full access too
// authenticated-read - owner gets full access, authenticated users get read access
// private - owner gets full access [default].
// public-read - owner gets full access, all others get read access.
// public-read-write - owner gets full access, all others get full access too.
// authenticated-read - owner gets full access, authenticated users get read access.
//
// Location valid values which are automatically derived from config endpoint
//
// [ us-west-1 | us-west-2 | eu-west-1 | eu-central-1 | ap-southeast-1 | ap-northeast-1 | ap-southeast-2 | sa-east-1 ]
// Default - US standard
func (a api) MakeBucket(bucket string, acl BucketACL) error {
func (a API) MakeBucket(bucket string, acl BucketACL) error {
if err := invalidBucketError(bucket); err != nil {
return err
}
@@ -739,19 +695,22 @@ func (a api) MakeBucket(bucket string, acl BucketACL) error {
if location == "us-east-1" {
location = ""
}
if location == "google" {
location = ""
}
return a.putBucket(bucket, string(acl), location)
}
// SetBucketACL set the permissions on an existing bucket using access control lists (ACL)
// SetBucketACL set the permissions on an existing bucket using access control lists (ACL).
//
// For example
//
// private - owner gets full access [default]
// public-read - owner gets full access, all others get read access
// public-read-write - owner gets full access, all others get full access too
// authenticated-read - owner gets full access, authenticated users get read access
// private - owner gets full access [default].
// public-read - owner gets full access, all others get read access.
// public-read-write - owner gets full access, all others get full access too.
// authenticated-read - owner gets full access, authenticated users get read access.
//
func (a api) SetBucketACL(bucket string, acl BucketACL) error {
func (a API) SetBucketACL(bucket string, acl BucketACL) error {
if err := invalidBucketError(bucket); err != nil {
return err
}
@@ -761,16 +720,16 @@ func (a api) SetBucketACL(bucket string, acl BucketACL) error {
return a.putBucketACL(bucket, string(acl))
}
// GetBucketACL get the permissions on an existing bucket
// GetBucketACL get the permissions on an existing bucket.
//
// Returned values are:
//
// private - owner gets full access
// public-read - owner gets full access, others get read access
// public-read-write - owner gets full access, others get full access too
// authenticated-read - owner gets full access, authenticated users get read access
// private - owner gets full access.
// public-read - owner gets full access, others get read access.
// public-read-write - owner gets full access, others get full access too.
// authenticated-read - owner gets full access, authenticated users get read access.
//
func (a api) GetBucketACL(bucket string) (BucketACL, error) {
func (a API) GetBucketACL(bucket string) (BucketACL, error) {
if err := invalidBucketError(bucket); err != nil {
return "", err
}
@@ -808,19 +767,19 @@ func (a api) GetBucketACL(bucket string) (BucketACL, error) {
}
}
// BucketExists verify if bucket exists and you have permission to access it
func (a api) BucketExists(bucket string) error {
// BucketExists verify if bucket exists and you have permission to access it.
func (a API) BucketExists(bucket string) error {
if err := invalidBucketError(bucket); err != nil {
return err
}
return a.headBucket(bucket)
}
// RemoveBucket deletes the bucket named in the URI
// NOTE: -
// All objects (including all object versions and delete markers)
// in the bucket must be deleted before successfully attempting this request
func (a api) RemoveBucket(bucket string) error {
// RemoveBucket deletes the bucket named in the URI.
//
// All objects (including all object versions and delete markers).
// in the bucket must be deleted before successfully attempting this request.
func (a API) RemoveBucket(bucket string) error {
if err := invalidBucketError(bucket); err != nil {
return err
}
@@ -832,13 +791,13 @@ type multiPartUploadCh struct {
Err error
}
func (a api) listMultipartUploadsRecursive(bucket, object string) <-chan multiPartUploadCh {
func (a API) listMultipartUploadsRecursive(bucket, object string) <-chan multiPartUploadCh {
ch := make(chan multiPartUploadCh, 1000)
go a.listMultipartUploadsRecursiveInRoutine(bucket, object, ch)
return ch
}
func (a api) listMultipartUploadsRecursiveInRoutine(bucket, object string, ch chan multiPartUploadCh) {
func (a API) listMultipartUploadsRecursiveInRoutine(bucket, object string, ch chan<- multiPartUploadCh) {
defer close(ch)
listMultipartUplResult, err := a.listMultipartUploads(bucket, "", "", object, "", 1000)
if err != nil {
@@ -876,9 +835,8 @@ func (a api) listMultipartUploadsRecursiveInRoutine(bucket, object string, ch ch
}
}
// listIncompleteUploadsInRoutine is an internal goroutine function called for listing objects
// This function feeds data into channel
func (a api) listIncompleteUploadsInRoutine(bucket, prefix string, recursive bool, ch chan ObjectMultipartStatCh) {
// listIncompleteUploadsInRoutine is an internal goroutine function called for listing objects.
func (a API) listIncompleteUploadsInRoutine(bucket, prefix string, recursive bool, ch chan<- ObjectMultipartStatCh) {
defer close(ch)
if err := invalidBucketError(bucket); err != nil {
ch <- ObjectMultipartStatCh{
@@ -901,7 +859,7 @@ func (a api) listIncompleteUploadsInRoutine(bucket, prefix string, recursive boo
return
}
for _, objectSt := range result.Uploads {
objectSt.Size, err = a.getMultipartSize(bucket, objectSt.Key, objectSt.UploadID)
objectSt.Size, err = a.getTotalMultipartSize(bucket, objectSt.Key, objectSt.UploadID)
if err != nil {
ch <- ObjectMultipartStatCh{
Stat: ObjectMultipartStat{},
@@ -934,7 +892,7 @@ func (a api) listIncompleteUploadsInRoutine(bucket, prefix string, recursive boo
multipartMarker = result.NextKeyMarker
uploadIDMarker = result.NextUploadIDMarker
for _, objectSt := range result.Uploads {
objectSt.Size, err = a.getMultipartSize(bucket, objectSt.Key, objectSt.UploadID)
objectSt.Size, err = a.getTotalMultipartSize(bucket, objectSt.Key, objectSt.UploadID)
if err != nil {
ch <- ObjectMultipartStatCh{
Stat: ObjectMultipartStat{},
@@ -962,30 +920,29 @@ func (a api) listIncompleteUploadsInRoutine(bucket, prefix string, recursive boo
}
}
// ListIncompleteUploads - (List incompletely uploaded multipart objects) - List some multipart objects or all recursively
// ListIncompleteUploads - List incompletely uploaded multipart objects.
//
// ListIncompleteUploads is a channel based API implemented to facilitate ease of usage of S3 API ListMultipartUploads()
// by automatically recursively traversing all multipart objects on a given bucket if specified.
//
// Your input paramters are just bucket, prefix and recursive
// Your input paramters are just bucket, prefix and recursive.
// If you enable recursive as 'true' this function will return back all the multipart objects in a given bucket.
//
// If you enable recursive as 'true' this function will return back all the multipart objects in a given bucket
// api := client.New(....)
// recursive := true
// for message := range api.ListIncompleteUploads("mytestbucket", "starthere", recursive) {
// fmt.Println(message.Stat)
// }
//
// eg:-
// api := client.New(....)
// for message := range api.ListIncompleteUploads("mytestbucket", "starthere", true) {
// fmt.Println(message.Stat)
// }
//
func (a api) ListIncompleteUploads(bucket, prefix string, recursive bool) <-chan ObjectMultipartStatCh {
func (a API) ListIncompleteUploads(bucket, prefix string, recursive bool) <-chan ObjectMultipartStatCh {
ch := make(chan ObjectMultipartStatCh, 1000)
go a.listIncompleteUploadsInRoutine(bucket, prefix, recursive, ch)
return ch
}
// listObjectsInRoutine is an internal goroutine function called for listing objects
// This function feeds data into channel
func (a api) listObjectsInRoutine(bucket, prefix string, recursive bool, ch chan ObjectStatCh) {
// listObjectsInRoutine is an internal goroutine function called for listing objects.
// This function feeds data into channel.
func (a API) listObjectsInRoutine(bucket, prefix string, recursive bool, ch chan<- ObjectStatCh) {
defer close(ch)
if err := invalidBucketError(bucket); err != nil {
ch <- ObjectStatCh{
@@ -1051,22 +1008,21 @@ func (a api) listObjectsInRoutine(bucket, prefix string, recursive bool, ch chan
}
}
// ListObjects - (List Objects) - List some objects or all recursively
// ListObjects - (List Objects) - List some objects or all recursively.
//
// ListObjects is a channel based API implemented to facilitate ease of usage of S3 API ListObjects()
// by automatically recursively traversing all objects on a given bucket if specified.
//
// Your input paramters are just bucket, prefix and recursive
// Your input paramters are just bucket, prefix and recursive.
// If you enable recursive as 'true' this function will return back all the objects in a given bucket.
//
// If you enable recursive as 'true' this function will return back all the objects in a given bucket
// api := client.New(....)
// recursive := true
// for message := range api.ListObjects("mytestbucket", "starthere", recursive) {
// fmt.Println(message.Stat)
// }
//
// eg:-
// api := client.New(....)
// for message := range api.ListObjects("mytestbucket", "starthere", true) {
// fmt.Println(message.Stat)
// }
//
func (a api) ListObjects(bucket string, prefix string, recursive bool) <-chan ObjectStatCh {
func (a API) ListObjects(bucket string, prefix string, recursive bool) <-chan ObjectStatCh {
ch := make(chan ObjectStatCh, 1000)
go a.listObjectsInRoutine(bucket, prefix, recursive, ch)
return ch
@@ -1074,7 +1030,7 @@ func (a api) ListObjects(bucket string, prefix string, recursive bool) <-chan Ob
// listBucketsInRoutine is an internal go routine function called for listing buckets
// This function feeds data into channel
func (a api) listBucketsInRoutine(ch chan BucketStatCh) {
func (a API) listBucketsInRoutine(ch chan<- BucketStatCh) {
defer close(ch)
listAllMyBucketListResults, err := a.listBuckets()
if err != nil {
@@ -1092,25 +1048,23 @@ func (a api) listBucketsInRoutine(ch chan BucketStatCh) {
}
}
// ListBuckets list of all buckets owned by the authenticated sender of the request
// ListBuckets list of all buckets owned by the authenticated sender of the request.
//
// NOTE:
// This call requires explicit authentication, no anonymous
// requests are allowed for listing buckets
// This call requires explicit authentication, no anonymous
// requests are allowed for listing buckets
//
// eg:-
// api := client.New(....)
// for message := range api.ListBuckets() {
// fmt.Println(message.Stat)
// }
// api := client.New(....)
// for message := range api.ListBuckets() {
// fmt.Println(message.Stat)
// }
//
func (a api) ListBuckets() <-chan BucketStatCh {
func (a API) ListBuckets() <-chan BucketStatCh {
ch := make(chan BucketStatCh, 100)
go a.listBucketsInRoutine(ch)
return ch
}
func (a api) removeIncompleteUploadInRoutine(bucket, object string, errorCh chan error) {
func (a API) removeIncompleteUploadInRoutine(bucket, object string, errorCh chan<- error) {
defer close(errorCh)
if err := invalidBucketError(bucket); err != nil {
errorCh <- err
@@ -1161,7 +1115,7 @@ func (a api) removeIncompleteUploadInRoutine(bucket, object string, errorCh chan
// RemoveIncompleteUpload - abort a specific in progress active multipart upload
// requires explicit authentication, no anonymous requests are allowed for multipart API
func (a api) RemoveIncompleteUpload(bucket, object string) <-chan error {
func (a API) RemoveIncompleteUpload(bucket, object string) <-chan error {
errorCh := make(chan error)
go a.removeIncompleteUploadInRoutine(bucket, object, errorCh)
return errorCh
+8 -8
View File
@@ -16,10 +16,10 @@
package minio
// BucketACL - bucket level access control
// BucketACL - bucket level access control.
type BucketACL string
// different types of ACL's currently supported for buckets
// Different types of ACL's currently supported for buckets.
const (
bucketPrivate = BucketACL("private")
bucketReadOnly = BucketACL("public-read")
@@ -27,7 +27,7 @@ const (
bucketAuthenticated = BucketACL("authenticated-read")
)
// String printer helper
// Stringify acl.
func (b BucketACL) String() string {
if string(b) == "" {
return "private"
@@ -35,7 +35,7 @@ func (b BucketACL) String() string {
return string(b)
}
// isValidBucketACL - is provided acl string supported
// isValidBucketACL - is provided acl string supported.
func (b BucketACL) isValidBucketACL() bool {
switch true {
case b.isPrivate():
@@ -54,22 +54,22 @@ func (b BucketACL) isValidBucketACL() bool {
}
}
// IsPrivate - is acl Private
// isPrivate - is acl Private.
func (b BucketACL) isPrivate() bool {
return b == bucketPrivate
}
// IsPublicRead - is acl PublicRead
// isPublicRead - is acl PublicRead.
func (b BucketACL) isReadOnly() bool {
return b == bucketReadOnly
}
// IsPublicReadWrite - is acl PublicReadWrite
// isPublicReadWrite - is acl PublicReadWrite.
func (b BucketACL) isPublic() bool {
return b == bucketPublic
}
// IsAuthenticated - is acl AuthenticatedRead
// isAuthenticated - is acl AuthenticatedRead.
func (b BucketACL) isAuthenticated() bool {
return b == bucketAuthenticated
}
+37 -38
View File
@@ -22,8 +22,8 @@ import (
"io"
)
// part - message structure for results from the MultiPart
type part struct {
// piece - container for each piece
type piece struct {
MD5Sum []byte
ReadSeeker io.ReadSeeker
Err error
@@ -31,33 +31,32 @@ type part struct {
Num int // part number
}
// skipPart - skipping uploaded parts
type skipPart struct {
md5sum []byte
partNumber int
// skipPiece - container for skip piece
type skipPiece struct {
md5sum []byte
pieceNumber int
}
// chopper reads from io.Reader, partitions the data into chunks of given chunksize, and sends
// each chunk as io.ReadSeeker to the caller over a channel
// chopper reads from io.Reader, partitions the data into pieces of given pieceSize, and sends
// each piece as io.ReadSeeker to the caller over a channel
//
// This method runs until an EOF or error occurs. If an error occurs,
// the method sends the error over the channel and returns.
// Before returning, the channel is always closed.
// This method runs until an EOF or an error occurs. Before returning, the channel is always closed.
//
// additionally this function also skips list of parts if provided
func chopper(reader io.Reader, chunkSize int64, skipParts []skipPart) <-chan part {
ch := make(chan part, 3)
go chopperInRoutine(reader, chunkSize, skipParts, ch)
// Additionally this function also skips list of pieces if provided
func chopper(reader io.Reader, pieceSize int64, skipPieces []skipPiece) <-chan piece {
ch := make(chan piece, 3)
go chopperInRoutine(reader, pieceSize, skipPieces, ch)
return ch
}
func chopperInRoutine(reader io.Reader, chunkSize int64, skipParts []skipPart, ch chan part) {
func chopperInRoutine(reader io.Reader, pieceSize int64, skipPieces []skipPiece, ch chan<- piece) {
defer close(ch)
p := make([]byte, chunkSize)
p := make([]byte, pieceSize)
n, err := io.ReadFull(reader, p)
if err == io.EOF || err == io.ErrUnexpectedEOF { // short read, only single part return
if err == io.EOF || err == io.ErrUnexpectedEOF {
// short read, only single piece return.
m := md5.Sum(p[0:n])
ch <- part{
ch <- piece{
MD5Sum: m[:],
ReadSeeker: bytes.NewReader(p[0:n]),
Err: nil,
@@ -66,24 +65,24 @@ func chopperInRoutine(reader io.Reader, chunkSize int64, skipParts []skipPart, c
}
return
}
// catastrophic error send error and return
// unknown error considered catastrophic error, return here.
if err != nil {
ch <- part{
ch <- piece{
ReadSeeker: nil,
Err: err,
Num: 0,
}
return
}
// send the first part
// send the first piece
var num = 1
md5SumBytes := md5.Sum(p)
sp := skipPart{
partNumber: num,
md5sum: md5SumBytes[:],
sp := skipPiece{
pieceNumber: num,
md5sum: md5SumBytes[:],
}
if !isPartNumberUploaded(sp, skipParts) {
ch <- part{
if !isPieceNumberUploaded(sp, skipPieces) {
ch <- piece{
MD5Sum: md5SumBytes[:],
ReadSeeker: bytes.NewReader(p),
Err: nil,
@@ -93,11 +92,11 @@ func chopperInRoutine(reader io.Reader, chunkSize int64, skipParts []skipPart, c
}
for err == nil {
var n int
p := make([]byte, chunkSize)
p := make([]byte, pieceSize)
n, err = io.ReadFull(reader, p)
if err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF { // catastrophic error
ch <- part{
ch <- piece{
ReadSeeker: nil,
Err: err,
Num: 0,
@@ -107,14 +106,14 @@ func chopperInRoutine(reader io.Reader, chunkSize int64, skipParts []skipPart, c
}
num++
md5SumBytes := md5.Sum(p[0:n])
sp := skipPart{
partNumber: num,
md5sum: md5SumBytes[:],
sp := skipPiece{
pieceNumber: num,
md5sum: md5SumBytes[:],
}
if isPartNumberUploaded(sp, skipParts) {
if isPieceNumberUploaded(sp, skipPieces) {
continue
}
ch <- part{
ch <- piece{
MD5Sum: md5SumBytes[:],
ReadSeeker: bytes.NewReader(p[0:n]),
Err: nil,
@@ -125,10 +124,10 @@ func chopperInRoutine(reader io.Reader, chunkSize int64, skipParts []skipPart, c
}
}
// to verify if partNumber is part of the skip part list
func isPartNumberUploaded(part skipPart, skipParts []skipPart) bool {
for _, p := range skipParts {
if p.partNumber == part.partNumber && bytes.Equal(p.md5sum, part.md5sum) {
// to verify if piece is already uploaded
func isPieceNumberUploaded(piece skipPiece, skipPieces []skipPiece) bool {
for _, p := range skipPieces {
if p.pieceNumber == piece.pieceNumber && bytes.Equal(p.md5sum, piece.md5sum) {
return true
}
}
+2 -3
View File
@@ -49,18 +49,17 @@ type ErrorResponse struct {
// ToErrorResponse returns parsed ErrorResponse struct, if input is nil or not ErrorResponse return value is nil
// this fuction is useful when some one wants to dig deeper into the error structures over the network.
//
// for example:
// For example:
//
// import s3 "github.com/minio/minio-go"
// ...
// ...
// ..., err := s3.GetObject(...)
// reader, stat, err := s3.GetObject(...)
// if err != nil {
// resp := s3.ToErrorResponse(err)
// fmt.Println(resp.ToXML())
// }
// ...
// ...
func ToErrorResponse(err error) *ErrorResponse {
switch err := err.(type) {
case ErrorResponse:
+49
View File
@@ -0,0 +1,49 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
import (
"io"
"time"
)
// CloudStorageAPI - Cloud Storage API interface
type CloudStorageAPI interface {
// Bucket Read/Write/Stat operations
MakeBucket(bucket string, cannedACL BucketACL) error
BucketExists(bucket string) error
RemoveBucket(bucket string) error
SetBucketACL(bucket string, cannedACL BucketACL) error
GetBucketACL(bucket string) (BucketACL, error)
ListBuckets() <-chan BucketStatCh
ListObjects(bucket, prefix string, recursive bool) <-chan ObjectStatCh
ListIncompleteUploads(bucket, prefix string, recursive bool) <-chan ObjectMultipartStatCh
// Object Read/Write/Stat operations
GetObject(bucket, object string) (io.ReadCloser, ObjectStat, error)
GetPartialObject(bucket, object string, offset, length int64) (io.ReadCloser, ObjectStat, error)
PutObject(bucket, object, contentType string, size int64, data io.Reader) error
StatObject(bucket, object string) (ObjectStat, error)
RemoveObject(bucket, object string) error
RemoveIncompleteUpload(bucket, object string) <-chan error
// Presigned operations
PresignedGetObject(bucket, object string, expires time.Duration) (string, error)
PresignedPutObject(bucket, object string, expires time.Duration) (string, error)
PresignedPostPolicy(*PostPolicy) (map[string]string, error)
}
+37 -13
View File
@@ -1,16 +1,38 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
import "io"
// ReadSeekCloser wraps an io.Reader returning a ReaderSeekerCloser
func ReadSeekCloser(r io.Reader) ReaderSeekerCloser {
return ReaderSeekerCloser{r}
type readSeekCloser struct {
r io.Reader
}
// ReaderSeekerCloser represents a reader that can also delegate io.Seeker and
// io.Closer interfaces to the underlying object if available.
type ReaderSeekerCloser struct {
r io.Reader
// NewReadSeekCloser wraps an io.Reader returning a ReadSeekCloser
func NewReadSeekCloser(r io.Reader) ReadSeekCloser {
return &readSeekCloser{r}
}
// ReadSeekCloser is the container
// that groups the basic Seek and Close methods.
type ReadSeekCloser interface {
io.Reader
io.Closer
io.Seeker
}
// Read reads up to len(p) bytes into p. It returns the number of bytes
@@ -27,7 +49,9 @@ type ReaderSeekerCloser struct {
// a non-zero number of bytes at the end of the input stream may
// return either err == EOF or err == nil. The next Read should
// return 0, EOF.
func (r ReaderSeekerCloser) Read(p []byte) (int, error) {
//
// If no io.Reader found nothing will be done.
func (r *readSeekCloser) Read(p []byte) (int, error) {
switch t := r.r.(type) {
case io.Reader:
return t.Read(p)
@@ -43,8 +67,8 @@ func (r ReaderSeekerCloser) Read(p []byte) (int, error) {
//
// Seeking to an offset before the start of the file is an error.
//
// If the ReaderSeekerCloser is not an io.Seeker nothing will be done.
func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) {
// If no io.Seeker found nothing will be done.
func (r *readSeekCloser) Seek(offset int64, whence int) (int64, error) {
switch t := r.r.(type) {
case io.Seeker:
return t.Seek(offset, whence)
@@ -52,13 +76,13 @@ func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) {
return int64(0), nil
}
// Close closes the ReaderSeekerCloser.
// Close closes the ReadSeekCloser.
//
// The behavior of Close after the first call is undefined.
// Specific implementations may document their own behavior.
//
// If the ReaderSeekerCloser is not an io.Closer nothing will be done.
func (r ReaderSeekerCloser) Close() error {
// If no io.Closer found nothing will be done.
func (r *readSeekCloser) Close() error {
switch t := r.r.(type) {
case io.Closer:
return t.Close()
+56 -25
View File
@@ -11,17 +11,26 @@ import (
// expirationDateFormat date format for expiration key in json policy
const expirationDateFormat = "2006-01-02T15:04:05.999Z"
// Policy explanation: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html
type policy struct {
// policyCondition explanation: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html
//
// Example:
// policyCondition {
// matchType: "$eq",
// key: "$Content-Type",
// value: "image/png",
// }
//
type policyCondition struct {
matchType string
key string
condition string
value string
}
// PostPolicy provides strict static type conversion and validation for Amazon S3's POST policy JSON string.
type PostPolicy struct {
expiration time.Time // expiration date and time of the POST policy.
policies []policy
expiration time.Time // expiration date and time of the POST policy.
conditions []policyCondition // collection of different policy conditions.
// contentLengthRange minimum and maximum allowable size for the uploaded content.
contentLengthRange struct {
min int
max int
@@ -34,7 +43,7 @@ type PostPolicy struct {
// NewPostPolicy instantiate new post policy
func NewPostPolicy() *PostPolicy {
p := &PostPolicy{}
p.policies = make([]policy, 0)
p.conditions = make([]policyCondition, 0)
p.formData = make(map[string]string)
return p
}
@@ -53,8 +62,14 @@ func (p *PostPolicy) SetKey(key string) error {
if strings.TrimSpace(key) == "" || key == "" {
return errors.New("key invalid")
}
policy := policy{"eq", "$key", key}
p.policies = append(p.policies, policy)
policyCond := policyCondition{
matchType: "eq",
condition: "$key",
value: key,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["key"] = key
return nil
}
@@ -64,8 +79,14 @@ func (p *PostPolicy) SetKeyStartsWith(keyStartsWith string) error {
if strings.TrimSpace(keyStartsWith) == "" || keyStartsWith == "" {
return errors.New("key-starts-with invalid")
}
policy := policy{"starts-with", "$key", keyStartsWith}
p.policies = append(p.policies, policy)
policyCond := policyCondition{
matchType: "starts-with",
condition: "$key",
value: keyStartsWith,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["key"] = keyStartsWith
return nil
}
@@ -75,8 +96,14 @@ func (p *PostPolicy) SetBucket(bucket string) error {
if strings.TrimSpace(bucket) == "" || bucket == "" {
return errors.New("bucket invalid")
}
policy := policy{"eq", "$bucket", bucket}
p.policies = append(p.policies, policy)
policyCond := policyCondition{
matchType: "eq",
condition: "$bucket",
value: bucket,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["bucket"] = bucket
return nil
}
@@ -86,8 +113,12 @@ func (p *PostPolicy) SetContentType(contentType string) error {
if strings.TrimSpace(contentType) == "" || contentType == "" {
return errors.New("contentType invalid")
}
policy := policy{"eq", "$Content-Type", contentType}
if err := p.addNewPolicy(policy); err != nil {
policyCond := policyCondition{
matchType: "eq",
condition: "$Content-Type",
value: contentType,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["Content-Type"] = contentType
@@ -111,11 +142,11 @@ func (p *PostPolicy) SetContentLength(min, max int) error {
}
// addNewPolicy - internal helper to validate adding new policies
func (p *PostPolicy) addNewPolicy(po policy) error {
if po.matchType == "" || po.key == "" || po.value == "" {
func (p *PostPolicy) addNewPolicy(policyCond policyCondition) error {
if policyCond.matchType == "" || policyCond.condition == "" || policyCond.value == "" {
return errors.New("policy invalid")
}
p.policies = append(p.policies, po)
p.conditions = append(p.conditions, policyCond)
return nil
}
@@ -127,21 +158,21 @@ func (p PostPolicy) String() string {
// marshalJSON provides Marshalled JSON
func (p PostPolicy) marshalJSON() []byte {
expirationStr := `"expiration":"` + p.expiration.Format(expirationDateFormat) + `"`
var policiesStr string
policies := []string{}
for _, po := range p.policies {
policies = append(policies, fmt.Sprintf("[\"%s\",\"%s\",\"%s\"]", po.matchType, po.key, po.value))
var conditionsStr string
conditions := []string{}
for _, po := range p.conditions {
conditions = append(conditions, fmt.Sprintf("[\"%s\",\"%s\",\"%s\"]", po.matchType, po.condition, po.value))
}
if p.contentLengthRange.min != 0 || p.contentLengthRange.max != 0 {
policies = append(policies, fmt.Sprintf("[\"content-length-range\", %d, %d]",
conditions = append(conditions, fmt.Sprintf("[\"content-length-range\", %d, %d]",
p.contentLengthRange.min, p.contentLengthRange.max))
}
if len(policies) > 0 {
policiesStr = `"conditions":[` + strings.Join(policies, ",") + "]"
if len(conditions) > 0 {
conditionsStr = `"conditions":[` + strings.Join(conditions, ",") + "]"
}
retStr := "{"
retStr = retStr + expirationStr + ","
retStr = retStr + policiesStr
retStr = retStr + conditionsStr
retStr = retStr + "}"
return []byte(retStr)
}
+27 -12
View File
@@ -1,3 +1,19 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
import (
@@ -17,8 +33,8 @@ type operation struct {
HTTPPath string
}
// request - a http request
type request struct {
// Request - a http request
type Request struct {
req *http.Request
config *Config
body io.ReadSeeker
@@ -26,7 +42,7 @@ type request struct {
}
// Do - start the request
func (r *request) Do() (resp *http.Response, err error) {
func (r *Request) Do() (resp *http.Response, err error) {
if r.config.AccessKeyID != "" && r.config.SecretAccessKey != "" {
if r.config.Signature.isV2() {
r.SignV2()
@@ -51,12 +67,12 @@ func (r *request) Do() (resp *http.Response, err error) {
}
// Set - set additional headers if any
func (r *request) Set(key, value string) {
func (r *Request) Set(key, value string) {
r.req.Header.Set(key, value)
}
// Get - get header values
func (r *request) Get(key string) string {
func (r *Request) Get(key string) string {
return r.req.Header.Get(key)
}
@@ -168,7 +184,7 @@ func (op *operation) getRequestURL(config Config) (url string) {
return
}
func newPresignedRequest(op *operation, config *Config, expires int64) (*request, error) {
func newPresignedRequest(op *operation, config *Config, expires int64) (*Request, error) {
// if no method default to POST
method := op.HTTPMethod
if method == "" {
@@ -192,7 +208,7 @@ func newPresignedRequest(op *operation, config *Config, expires int64) (*request
}
// save for subsequent use
r := new(request)
r := new(Request)
r.config = config
r.expires = expires
r.req = req
@@ -202,7 +218,7 @@ func newPresignedRequest(op *operation, config *Config, expires int64) (*request
}
// newUnauthenticatedRequest - instantiate a new unauthenticated request
func newUnauthenticatedRequest(op *operation, config *Config, body io.Reader) (*request, error) {
func newUnauthenticatedRequest(op *operation, config *Config, body io.Reader) (*Request, error) {
// if no method default to POST
method := op.HTTPMethod
if method == "" {
@@ -234,7 +250,7 @@ func newUnauthenticatedRequest(op *operation, config *Config, body io.Reader) (*
}
// save for subsequent use
r := new(request)
r := new(Request)
r.req = req
r.config = config
@@ -242,7 +258,7 @@ func newUnauthenticatedRequest(op *operation, config *Config, body io.Reader) (*
}
// newRequest - instantiate a new request
func newRequest(op *operation, config *Config, body io.ReadSeeker) (*request, error) {
func newRequest(op *operation, config *Config, body io.ReadSeeker) (*Request, error) {
// if no method default to POST
method := op.HTTPMethod
if method == "" {
@@ -250,7 +266,6 @@ func newRequest(op *operation, config *Config, body io.ReadSeeker) (*request, er
}
u := op.getRequestURL(*config)
// get a new HTTP request, for the requested method
req, err := http.NewRequest(method, u, nil)
if err != nil {
@@ -274,7 +289,7 @@ func newRequest(op *operation, config *Config, body io.ReadSeeker) (*request, er
}
// save for subsequent use
r := new(request)
r := new(Request)
r.config = config
r.req = req
r.body = body
+24 -20
View File
@@ -1,5 +1,5 @@
/*
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 2015 Minio, Inc.
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,8 +31,9 @@ import (
"time"
)
// PreSignV2 - presign the request in following style.
// https://${S3_BUCKET}.s3.amazonaws.com/${S3_OBJECT}?AWSAccessKeyId=${S3_ACCESS_KEY}&Expires=${TIMESTAMP}&Signature=${SIGNATURE}
func (r *request) PreSignV2() (string, error) {
func (r *Request) PreSignV2() (string, error) {
if r.config.AccessKeyID == "" || r.config.SecretAccessKey == "" {
return "", errors.New("presign requires accesskey and secretkey")
}
@@ -68,7 +69,8 @@ func (r *request) PreSignV2() (string, error) {
return r.req.URL.String(), nil
}
func (r *request) PostPresignSignatureV2(policyBase64 string) string {
// PostPresignSignatureV2 - presigned signature for PostPolicy request
func (r *Request) PostPresignSignatureV2(policyBase64 string) string {
hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey))
hm.Write([]byte(policyBase64))
signature := base64.StdEncoding.EncodeToString(hm.Sum(nil))
@@ -91,24 +93,24 @@ func (r *request) PostPresignSignatureV2(policyBase64 string) string {
//
// CanonicalizedProtocolHeaders = <described below>
// SignV2 the request before Do() (version 2.0)
func (r *request) SignV2() {
// Add date if not present
// SignV2 sign the request before Do() (AWS Signature Version 2).
func (r *Request) SignV2() {
// Add date if not present.
if date := r.Get("Date"); date == "" {
r.Set("Date", time.Now().UTC().Format(http.TimeFormat))
r.Set("X-Amz-Date", time.Now().UTC().Format(http.TimeFormat))
}
// Calculate HMAC for secretAccessKey
// Calculate HMAC for secretAccessKey.
hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey))
hm.Write([]byte(r.getStringToSignV2()))
// prepare auth header
// prepare auth header.
authHeader := new(bytes.Buffer)
authHeader.WriteString(fmt.Sprintf("AWS %s:", r.config.AccessKeyID))
encoder := base64.NewEncoder(base64.StdEncoding, authHeader)
encoder.Write(hm.Sum(nil))
encoder.Close()
// Set Authorization header
// Set Authorization header.
r.req.Header.Set("Authorization", authHeader.String())
}
@@ -117,32 +119,34 @@ func (r *request) SignV2() {
// StringToSign = HTTP-Verb + "\n" +
// Content-MD5 + "\n" +
// Content-Type + "\n" +
// Date + "\n" +
// Date(X-Amz-Date) + "\n" +
// CanonicalizedProtocolHeaders +
// CanonicalizedResource;
func (r *request) getStringToSignV2() string {
func (r *Request) getStringToSignV2() string {
buf := new(bytes.Buffer)
// write standard headers
// write standard headers.
r.writeDefaultHeaders(buf)
// write canonicalized protocol headers if any
// write canonicalized protocol headers if any.
r.writeCanonicalizedHeaders(buf)
// write canonicalized Query resources if any
// write canonicalized Query resources if any.
r.writeCanonicalizedResource(buf)
return buf.String()
}
func (r *request) writeDefaultHeaders(buf *bytes.Buffer) {
// writeDefaultHeader - write all default necessary headers
func (r *Request) writeDefaultHeaders(buf *bytes.Buffer) {
buf.WriteString(r.req.Method)
buf.WriteByte('\n')
buf.WriteString(r.req.Header.Get("Content-MD5"))
buf.WriteByte('\n')
buf.WriteString(r.req.Header.Get("Content-Type"))
buf.WriteByte('\n')
buf.WriteString(r.req.Header.Get("Date"))
buf.WriteString(r.req.Header.Get("X-Amz-Date"))
buf.WriteByte('\n')
}
func (r *request) writeCanonicalizedHeaders(buf *bytes.Buffer) {
// writeCanonicalizedHeaders - write canonicalized headers.
func (r *Request) writeCanonicalizedHeaders(buf *bytes.Buffer) {
var protoHeaders []string
vals := make(map[string][]string)
for k, vv := range r.req.Header {
@@ -205,7 +209,7 @@ var resourceList = []string{
// CanonicalizedResource = [ "/" + Bucket ] +
// <HTTP-Request-URI, from the protocol name up to the query string> +
// [ sub-resource, if present. For example "?acl", "?location", "?logging", or "?torrent"];
func (r *request) writeCanonicalizedResource(buf *bytes.Buffer) error {
func (r *Request) writeCanonicalizedResource(buf *bytes.Buffer) error {
requestURL := r.req.URL
if r.config.isVirtualStyle {
for k, v := range regions {
@@ -223,7 +227,7 @@ func (r *request) writeCanonicalizedResource(buf *bytes.Buffer) error {
if requestURL.RawQuery != "" {
var n int
vals, _ := url.ParseQuery(requestURL.RawQuery)
// loop through all the supported resourceList
// loop through all the supported resourceList.
for _, resource := range resourceList {
if vv, ok := vals[resource]; ok && len(vv) > 0 {
n++
+20 -15
View File
@@ -27,6 +27,7 @@ import (
"time"
)
// signature and API related constants.
const (
authHeader = "AWS4-HMAC-SHA256"
iso8601DateFormat = "20060102T150405Z"
@@ -34,7 +35,7 @@ const (
)
///
/// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258
/// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258.
///
/// User-Agent:
///
@@ -69,7 +70,7 @@ var ignoredHeaders = map[string]bool{
}
// getHashedPayload get the hexadecimal value of the SHA256 hash of the request payload
func (r *request) getHashedPayload() string {
func (r *Request) getHashedPayload() string {
hash := func() string {
switch {
case r.expires != 0:
@@ -88,8 +89,8 @@ func (r *request) getHashedPayload() string {
return hashedPayload
}
// getCanonicalHeaders generate a list of request headers with their values
func (r *request) getCanonicalHeaders() string {
// getCanonicalHeaders generate a list of request headers for signature.
func (r *Request) getCanonicalHeaders() string {
var headers []string
vals := make(map[string][]string)
for k, vv := range r.req.Header {
@@ -123,8 +124,9 @@ func (r *request) getCanonicalHeaders() string {
return buf.String()
}
// getSignedHeaders generate a string i.e alphabetically sorted, semicolon-separated list of lowercase request header names
func (r *request) getSignedHeaders() string {
// getSignedHeaders generate all signed request headers.
// i.e alphabetically sorted, semicolon-separated list of lowercase request header names
func (r *Request) getSignedHeaders() string {
var headers []string
for k := range r.req.Header {
if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok {
@@ -137,7 +139,7 @@ func (r *request) getSignedHeaders() string {
return strings.Join(headers, ";")
}
// getCanonicalRequest generate a canonical request of style
// getCanonicalRequest generate a canonical request of style.
//
// canonicalRequest =
// <HTTPMethod>\n
@@ -147,7 +149,7 @@ func (r *request) getSignedHeaders() string {
// <SignedHeaders>\n
// <HashedPayload>
//
func (r *request) getCanonicalRequest(hashedPayload string) string {
func (r *Request) getCanonicalRequest(hashedPayload string) string {
r.req.URL.RawQuery = strings.Replace(r.req.URL.Query().Encode(), "+", "%20", -1)
canonicalRequest := strings.Join([]string{
r.req.Method,
@@ -160,16 +162,17 @@ func (r *request) getCanonicalRequest(hashedPayload string) string {
return canonicalRequest
}
// getStringToSign a string based on selected query values
func (r *request) getStringToSignV4(canonicalRequest string, t time.Time) string {
// getStringToSign a string based on selected query values.
func (r *Request) getStringToSignV4(canonicalRequest string, t time.Time) string {
stringToSign := authHeader + "\n" + t.Format(iso8601DateFormat) + "\n"
stringToSign = stringToSign + getScope(r.config.Region, t) + "\n"
stringToSign = stringToSign + hex.EncodeToString(sum256([]byte(canonicalRequest)))
return stringToSign
}
// Presign the request, in accordance with - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
func (r *request) PreSignV4() (string, error) {
// PreSignV4 presign the request, in accordance with
// http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html.
func (r *Request) PreSignV4() (string, error) {
if r.config.AccessKeyID == "" && r.config.SecretAccessKey == "" {
return "", errors.New("presign requires accesskey and secretkey")
}
@@ -177,14 +180,16 @@ func (r *request) PreSignV4() (string, error) {
return r.req.URL.String(), nil
}
func (r *request) PostPresignSignatureV4(policyBase64 string, t time.Time) string {
// PostPresignSignatureV4 - presigned signature for PostPolicy requests.
func (r *Request) PostPresignSignatureV4(policyBase64 string, t time.Time) string {
signingkey := getSigningKey(r.config.SecretAccessKey, r.config.Region, t)
signature := getSignature(signingkey, policyBase64)
return signature
}
// SignV4 the request before Do(), in accordance with - http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html
func (r *request) SignV4() {
// SignV4 sign the request before Do(), in accordance with
// http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html.
func (r *Request) SignV4() {
query := r.req.URL.Query()
if r.expires != 0 {
query.Set("X-Amz-Algorithm", authHeader)
+2 -2
View File
@@ -29,8 +29,8 @@
},
{
"path": "github.com/minio/minio-go",
"revision": "05139b2e8324ca7778a6982b9f69cfc23e97210b",
"revisionTime": "2015-11-06T23:34:37-08:00"
"revision": "4038ad42792060c25e80badf20ea8f5fd24da28b",
"revisionTime": "2015-11-09T21:12:17-08:00"
},
{
"path": "github.com/minio/minio-xl/pkg/probe",