aws.go 1.75 KB
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
package aws

import (
	"context"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"hilo/common/httpclient"
	"hilo/common/util"

	//"hilo/biz/util"
	//hiloCfg "hilo/common/config"
	//"hilo/common/mylogrus"
	"log"
	"mime/multipart"
)

var Global *Aws

type (
	Config struct {
		Bucket string
		Cdn    string
		Dir    string
	}
	Aws struct {
		Config *Config
		Cfg    aws.Config
	}
)

func NewAWS(conf *Config) *Aws {
	// Load the Shared AWS Configuration (~/.aws/config)
	a := &Aws{
		Config: conf,
	}
	var err error = nil
	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		log.Fatal(err)
	}
	a.Cfg = cfg
	return a
}

func SetAws(a *Aws) {
	Global = a
}

func (a *Aws) UploadImage(imagPath string) (string, error) {
	resp, _ := httpclient.Default.Get(imagPath)

	// Create an Amazon S3 service client
	client := s3.NewFromConfig(a.Cfg)

	fileName := a.Config.Dir + "image/" + util.GetRandStrByUUID()
	ct := "image/jpeg"
	_, err := client.PutObject(context.TODO(), &s3.PutObjectInput{
		Bucket:        aws.String(a.Config.Bucket),
		Key:           aws.String(fileName),
		Body:          resp.Body,
		ContentLength: resp.ContentLength,
		ContentType:   &ct,
	})
	if err != nil {
		return "", err
	}
	return fileName, nil
}

func (a *Aws) UploadImageFile(imagFile multipart.File, t string, contentType *string) (string, error) {
	// Create an Amazon S3 service client
	client := s3.NewFromConfig(a.Cfg)
	fileName := a.Config.Dir + "manager/" + t
	_, err := client.PutObject(context.TODO(), &s3.PutObjectInput{
		Bucket:      aws.String(a.Config.Bucket),
		Key:         aws.String(fileName),
		Body:        imagFile,
		ContentType: contentType,
	})
	if err != nil {
		return "", err
	}
	return fileName, nil
}