127 lines
2.6 KiB
Go
127 lines
2.6 KiB
Go
package aws
|
|
|
|
import (
|
|
"io"
|
|
"io/ioutil"
|
|
"strings"
|
|
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
"github.com/aws/aws-sdk-go/aws/credentials"
|
|
"github.com/aws/aws-sdk-go/aws/session"
|
|
"github.com/aws/aws-sdk-go/service/s3"
|
|
)
|
|
|
|
type Config struct {
|
|
AwsAccessKeyId string `toml:"access_key_id" json:"access_key_id"`
|
|
AwsSecretAccessKey string `toml:"secret_access_key" json:"secret_access_id"`
|
|
AwsBuckets string `toml:"buckets" json:"buckets"`
|
|
AwsRegion string `toml:"region" json:"region"`
|
|
}
|
|
|
|
func NewS3Session(c *Config) *session.Session {
|
|
cfg := aws.NewConfig().WithRegion(c.AwsRegion).WithCredentials(
|
|
credentials.NewStaticCredentials(
|
|
c.AwsAccessKeyId,
|
|
c.AwsSecretAccessKey,
|
|
""),
|
|
)
|
|
s, _ := session.NewSession(cfg)
|
|
return s
|
|
}
|
|
|
|
func Put(c Config, key, contentType string, input io.ReadSeeker) error {
|
|
s := NewS3Session(&c)
|
|
client := s3.New(s)
|
|
_, err := client.PutObject(
|
|
&s3.PutObjectInput{
|
|
Bucket: aws.String(c.AwsBuckets),
|
|
Key: aws.String(key),
|
|
ContentType: aws.String(contentType),
|
|
Body: input,
|
|
CacheControl: aws.String("max-age=2592000"),
|
|
},
|
|
)
|
|
return err
|
|
}
|
|
|
|
func Del(c Config, key string) error {
|
|
s := NewS3Session(&c)
|
|
client := s3.New(s)
|
|
|
|
arg := &s3.DeleteObjectInput{
|
|
Bucket: aws.String(c.AwsBuckets),
|
|
Key: aws.String(key),
|
|
}
|
|
|
|
_, err := client.DeleteObject(arg)
|
|
return err
|
|
}
|
|
|
|
func Get(c Config, key string) (string, []byte, error) {
|
|
s := NewS3Session(&c)
|
|
client := s3.New(s)
|
|
|
|
arg := &s3.GetObjectInput{
|
|
Bucket: aws.String(c.AwsBuckets),
|
|
Key: aws.String(key),
|
|
}
|
|
|
|
ret, err := client.GetObject(arg)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
|
|
if ret != nil {
|
|
defer ret.Body.Close()
|
|
}
|
|
|
|
contentType := ""
|
|
if ret != nil && ret.ContentType != nil {
|
|
contentType = *ret.ContentType
|
|
}
|
|
|
|
b, err := ioutil.ReadAll(ret.Body)
|
|
|
|
return contentType, b, err
|
|
}
|
|
|
|
func List(c Config, prefix string, file string, count int64) ([]string, error) {
|
|
s := NewS3Session(&c)
|
|
client := s3.New(s)
|
|
|
|
input := &s3.ListObjectsInput{
|
|
Bucket: aws.String(c.AwsBuckets),
|
|
Prefix: aws.String(prefix),
|
|
Marker: aws.String(file),
|
|
MaxKeys: aws.Int64(count),
|
|
}
|
|
|
|
ret, err := client.ListObjects(input)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
keys := []string{}
|
|
|
|
for _, obj := range ret.Contents {
|
|
if strings.HasSuffix(*obj.Key, "/") {
|
|
continue
|
|
}
|
|
keys = append(keys, *obj.Key)
|
|
}
|
|
return keys, nil
|
|
}
|
|
|
|
func Copy(c Config, source, key string) error {
|
|
s := NewS3Session(&c)
|
|
client := s3.New(s)
|
|
|
|
_, err := client.CopyObject(&s3.CopyObjectInput{
|
|
Bucket: aws.String(c.AwsBuckets),
|
|
CopySource: aws.String(source),
|
|
Key: aws.String(key),
|
|
})
|
|
return err
|
|
|
|
}
|