108 lines
2.2 KiB
Go
108 lines
2.2 KiB
Go
package file
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"mime"
|
|
"path"
|
|
"time"
|
|
|
|
"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"
|
|
)
|
|
|
|
const (
|
|
id = "AKIAJM3XLDNUBXUY36EQ"
|
|
secret = "DZ1Y1ETQlCEc/6JlyW2mxdE8SAfPsmSSrpxGzcTi"
|
|
region = "ap-east-1"
|
|
bucket = "tknk.zahokc.cn"
|
|
URL = "https://tknk.zahokc.cn.s3.ap-east-1.amazonaws.com/"
|
|
APPFlag = "ys-7527/"
|
|
)
|
|
|
|
var (
|
|
endpoint = ""
|
|
disableSSL = true
|
|
AwsSession *session.Session
|
|
)
|
|
|
|
func init() {
|
|
NewSession()
|
|
}
|
|
|
|
/**
|
|
* 创建session
|
|
*/
|
|
func NewSession() {
|
|
creds := credentials.NewStaticCredentials(id, secret, "")
|
|
config := &aws.Config{
|
|
Region: aws.String(region),
|
|
Endpoint: &endpoint,
|
|
S3ForcePathStyle: aws.Bool(true),
|
|
Credentials: creds,
|
|
DisableSSL: &disableSSL,
|
|
}
|
|
se, err := session.NewSession(config)
|
|
AwsSession = se
|
|
if err != nil {
|
|
fmt.Printf("create session fail %+v", err)
|
|
return
|
|
}
|
|
}
|
|
|
|
func ListAllBucket() {
|
|
svc := s3.New(AwsSession)
|
|
resp, err := svc.ListBuckets(&s3.ListBucketsInput{})
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
} else {
|
|
fmt.Println(resp.Buckets)
|
|
}
|
|
}
|
|
|
|
/**上传文件*/
|
|
func PutObject(key string, content []byte, ttl int64) error {
|
|
svc := s3.New(AwsSession)
|
|
params := &s3.PutObjectInput{
|
|
Bucket: aws.String(bucket), // Required
|
|
Key: aws.String(key), // Required
|
|
ACL: aws.String("public-read"), //设置成公共读。
|
|
Body: bytes.NewReader(content),
|
|
}
|
|
duration := time.Duration(ttl * 1000)
|
|
ext := path.Ext(key)
|
|
if ttl > 0 {
|
|
params.SetExpires(time.Now().Add(duration))
|
|
}
|
|
if ext != "" {
|
|
contentType := mime.TypeByExtension(ext)
|
|
if contentType != "" {
|
|
params.SetContentType(contentType)
|
|
}
|
|
}
|
|
_, err := svc.PutObject(params)
|
|
//svc.PutObjectLegalHold
|
|
return err
|
|
}
|
|
|
|
func GetObject(key string) ([]byte, error) {
|
|
svc := s3.New(AwsSession)
|
|
params := &s3.GetObjectInput{
|
|
Bucket: aws.String(bucket), // Required
|
|
Key: aws.String(key), // Require
|
|
}
|
|
getObjectOutput, err := svc.GetObject(params)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
data, err := io.ReadAll(getObjectOutput.Body)
|
|
getObjectOutput.Body.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return data, nil
|
|
}
|