Home Download Docs Code Community
     1	/*
     2	Copyright 2011 The Perkeep Authors
     3	
     4	Licensed under the Apache License, Version 2.0 (the "License");
     5	you may not use this file except in compliance with the License.
     6	You may obtain a copy of the License at
     7	
     8	     http://www.apache.org/licenses/LICENSE-2.0
     9	
    10	Unless required by applicable law or agreed to in writing, software
    11	distributed under the License is distributed on an "AS IS" BASIS,
    12	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13	See the License for the specific language governing permissions and
    14	limitations under the License.
    15	*/
    16	
    17	package s3
    18	
    19	import (
    20		"context"
    21		"io"
    22	
    23		"github.com/aws/aws-sdk-go/aws"
    24		"github.com/aws/aws-sdk-go/service/s3/s3manager"
    25		"go4.org/readerutil"
    26		"perkeep.org/pkg/blob"
    27	)
    28	
    29	func (sto *s3Storage) ReceiveBlob(ctx context.Context, b blob.Ref, source io.Reader) (sr blob.SizedRef, err error) {
    30		if faultReceive.FailErr(&err) {
    31			return
    32		}
    33	
    34		// unfortunately, the s3manager doesn't tell us the size of the file it uploads.
    35		// It's still worth using because it handles multipart uploads correctly.
    36		// In order to still get the size, we check if the given reader provides its
    37		// size, and if not count the data uploaded as we go.
    38		if size, ok := readerutil.Size(source); ok {
    39			if err := sto.doUpload(ctx, b, source); err != nil {
    40				return sr, err
    41			}
    42			return blob.SizedRef{Ref: b, Size: uint32(size)}, nil
    43		}
    44	
    45		cr := readerutil.CountingReader{
    46			Reader: source,
    47			N:      aws.Int64(0),
    48		}
    49		if err = sto.doUpload(ctx, b, cr); err != nil {
    50			return sr, err
    51		}
    52		return blob.SizedRef{Ref: b, Size: uint32(*cr.N)}, nil
    53	}
    54	
    55	func (sto *s3Storage) doUpload(ctx context.Context, b blob.Ref, r io.Reader) error {
    56		uploader := s3manager.NewUploaderWithClient(sto.client)
    57	
    58		_, err := uploader.UploadWithContext(ctx, &s3manager.UploadInput{
    59			Bucket: &sto.bucket,
    60			Key:    aws.String(sto.dirPrefix + b.String()),
    61			Body:   r,
    62		})
    63		return err
    64	}
Website layout inspired by memcached.
Content by the authors.