This commit is contained in:
mr.x
2020-11-21 21:51:07 +08:00
commit 646e2f9410
10 changed files with 430 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.idea

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

8
README.md Normal file
View File

@@ -0,0 +1,8 @@
# golang_aliyunoss
#install
go get github.com/mrxfantasy/golang_aliyunoss
#example

23
example.go Normal file
View File

@@ -0,0 +1,23 @@
package main
import "fmt"
var ossClient *AliOssClient
func init() {
ossConfig := &AliOssConfig{
EndPoint: "oss-cn-shenzhen.aliyuncs.com",
AccessKeyId: "",
AccessKeySecret: "",
BucketName: "",
}
ossClient = ossConfig.CreateOssConnect()
}
func main() {
uri := ossClient.Put("logo/","./File/3HaqWaOzJWD86DDvZD9Pmn9VUEOBOBbuWackGOXb (2).jpeg")
fmt.Println(uri)
}

98
file.go Normal file
View File

@@ -0,0 +1,98 @@
package main
import (
"fmt"
uuid "github.com/satori/go.uuid"
"io/ioutil"
"mime/multipart"
"os"
"path/filepath"
"reflect"
"strings"
)
type OssFile struct {
FileByte []byte
FileOldName string
FileNewName string
FileType string
File interface{}
}
type OssFileInterface interface {
FileTypeTransForm() (*OssFile,error)
GetFileType() *OssFile
}
// file type transform
//@title 文件类型转换
func (ossFile *OssFile) FileTypeTransForm() (*OssFile,error) {
var err error
switch ossFile.File.(type) {
case *os.File:
ossFile.FileByte,err = ioutil.ReadAll(ossFile.File.(*os.File))
if err != nil {
panic("read os type file failed:" + err.Error())
}
_,ossFile.FileOldName = filepath.Split(ossFile.File.(*os.File).Name())
case *multipart.FileHeader:
fileResources,err := ossFile.File.(*multipart.FileHeader).Open()
if err != nil {
panic("open multipart file failed:" + err.Error())
}
defer fileResources.Close()
ossFile.FileByte,err = ioutil.ReadAll(fileResources)
if err != nil {
panic("read multipart file failed:" + err.Error())
}
ossFile.FileOldName = ossFile.File.(*multipart.FileHeader).Filename
case string:
newFile,err := os.Open(ossFile.File.(string))
if err != nil {
panic("open file path failed:" + err.Error())
}
defer newFile.Close()
ossFile.FileByte,err = ioutil.ReadAll(newFile)
_,ossFile.FileOldName = filepath.Split(newFile.Name())
default:
fmt.Println(reflect.TypeOf(ossFile.File))
panic("file type error" )
}
ossFile.GetFileType()
return ossFile,nil
}
//split file type and generate file name
//截取文件类型
func (ossFile *OssFile) GetFileType() *OssFile {
//from oldFileName split file type
fileTypeSufIndex := strings.Index(ossFile.FileOldName,".")
fileType := ossFile.FileOldName[fileTypeSufIndex:]
ossFile.FileType = fileType
//generate only file name
ossFile.FileNewName = uuid.NewV5(uuid.NewV4(),ossFile.FileOldName).String() + ossFile.FileType
return ossFile
}

9
go.mod Normal file
View File

@@ -0,0 +1,9 @@
module aliyun_oss
go 1.15
require (
github.com/aliyun/aliyun-oss-go-sdk v2.1.5+incompatible
github.com/satori/go.uuid v1.2.0
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e // indirect
)

7
go.sum Normal file
View File

@@ -0,0 +1,7 @@
github.com/aliyun/aliyun-oss-go-sdk v1.9.8 h1:BOflvK0Zs/zGmoabyFIzTg5c3kguktWTXEwewwbuba0=
github.com/aliyun/aliyun-oss-go-sdk v2.1.5+incompatible h1:v5yDfjkRY/kOxu05gkh0/D/2wYxbTFCoTr3JqFI0FLE=
github.com/aliyun/aliyun-oss-go-sdk v2.1.5+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e h1:EHBhcS0mlXEAVwNyO2dLfjToGsyY4j24pTs2ScHnX7s=
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=

116
ossClient.go Normal file
View File

@@ -0,0 +1,116 @@
package main
import (
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"strings"
)
type AliOssConfig struct {
EndPoint string `json:"end_point"`
AccessKeyId string `json:"access_id"`
AccessKeySecret string `json:"access_key"`
BucketName string `json:"bucket_name"`
Domain string `json:"domain"`
OriginalFileName bool `json:"only_file_name"`
}
type AliOssConfigInterface interface {
CheckConfig()
CreateOssConnect() *AliOssClient
GetAccessibleUrl() string
}
//check AliOssConfig value is exists
func (coon *AliOssConfig) CheckConfig() {
//check endPoint
if coon.EndPoint == "" || len(coon.EndPoint) <= 0 {
panic("endPoint value can not empty")
}
//check endPoint http prefix if empty default http
if strings.HasPrefix(coon.EndPoint,"https://") == false && strings.HasPrefix(coon.EndPoint,"http://") == false {
coon.EndPoint = "http://" + coon.EndPoint
}
//check access secret
if coon.AccessKeyId == "" || len(coon.AccessKeyId) <= 0 {
panic("accessKeyId can not empty")
}
//check access key
if coon.AccessKeySecret == "" || len(coon.AccessKeySecret) <= 0 {
panic("accessKeySecret can not empty")
}
//check bucket name
if coon.BucketName == "" || len(coon.BucketName) <= 0 {
panic("bucketName can not empty")
}
}
//en: create oss connect client
//创建阿里云oss 链接客户端
func (coon *AliOssConfig) CreateOssConnect() *AliOssClient {
//config check
coon.CheckConfig()
//connect oss client/ init oss client
//链接oss客户端/初始化oss客户端
connect, err := oss.New(coon.EndPoint, coon.AccessKeyId, coon.AccessKeySecret)
if err != nil {
panic("connect oss client failed:" + err.Error())
}
//选择桶
//choose oss bucket
client,err := connect.Bucket(coon.BucketName)
if err != nil {
panic("choose bucket name failed:" + err.Error())
}
//拼接可访问地址
//get accessible url
var domain string
domain = coon.GetAccessibleUrl()
return &AliOssClient{
Domain: domain,
OriginalFileName: coon.OriginalFileName,
Client: client,
}
}
//get oss accessible url
//拼接阿里云oss可访问地址
func (coon *AliOssConfig) GetAccessibleUrl() string {
var domain string
//select endpoint http prefix
//查找oss endpoint 的http 前缀
endPointUriPrefixIndex := strings.Index(coon.EndPoint,"://")
endPointUriPrefix := coon.EndPoint[:endPointUriPrefixIndex]
//截取出endPoint
//split oss public domain '://' length is 3
endPoint := coon.EndPoint[endPointUriPrefixIndex + 3:]
//judge accessible uri value is exists if not. accessible uri = endPointUriSuf + :// + bucketName + . + endPoint
//example: http://test.oss-cn-shenzhen.aliyuncs.com
//判断可访问地址是否配置
if coon.Domain == "" || len(coon.Domain) <= 0 {
domain = endPointUriPrefix + "://" + coon.BucketName + "." + endPoint
//not exists
} else {
//judge domain is http prefix and https prefix
if strings.HasPrefix("http://",coon.Domain) == false && strings.HasPrefix("https://",coon.Domain) == false {
domain = endPointUriPrefix + "://" + coon.Domain
} else {
domain = coon.Domain
}
}
return domain
}

98
ossOperation.go Normal file
View File

@@ -0,0 +1,98 @@
package main
import (
"bytes"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
type AliOssClient struct {
Domain string
OriginalFileName bool
Client *oss.Bucket
}
//推送文件到oss
//params: ossDir string `oss dir [要推送到的oss目录]` example: test/20201121/
//params: file interface `upload file resource [文件资源]`
//return string `oss file accessible uri [可访问地址]`
func (client *AliOssClient) Put(ossDir string, file interface{}) string {
//file to []byte
//文件转字节流
uploadFile := &OssFile{
File: file,
}
ossFile,err := uploadFile.FileTypeTransForm()
if err != nil {
panic("transfer file failed" + err.Error())
}
//ossPath = oss dir + upload file name
//example: oss dir is diy ==== test/20201121/
//time.Now().Format("20060102")
//ossPath := path + fileName
var ossPath string
//judge is use origin file name if false fileName = fileNewName (is a only name) else file init name
if client.OriginalFileName == false {
ossPath = ossDir + ossFile.FileNewName
} else {
ossPath = ossDir + ossFile.FileOldName
}
//upload file to oss
err = client.Client.PutObject(ossPath,bytes.NewReader(ossFile.FileByte))
if err != nil {
panic("put file to oss failed:" + err.Error())
}
return client.Domain + "/" + ossPath
}
//校验文件是否已经存在
//check file already exists in oss server
//params: ossFilePath string `file oss path [文件的oss的路径]`
func (client *AliOssClient) HasExists(ossFilePath string) bool {
//oss check fun
isExists,err := client.Client.IsObjectExist(ossFilePath)
if err != nil {
panic("check file in oss is exists failed:" + err.Error())
}
return isExists
}
//删除文件-单文件删除
//delete one file in oss
//params ossPath string `file oss path [文件的oss路径]`
//return bool
func (client *AliOssClient) Delete(ossFilePath string) bool {
//oss delete one file fun
err := client.Client.DeleteObject(ossFilePath)
if err != nil {
panic("delete file "+ ossFilePath +" failed:" + err.Error())
}
return true
}
//删除文件-多文件删除
//delete more file in oss
//params ossPath []string `file oss path array [文件的oss路径数组]`
//return bool
func (client *AliOssClient) DeleteMore(ossFilePath []string) bool {
//oss delete more file fun
_,err := client.Client.DeleteObjects(ossFilePath)
if err != nil {
panic("delete more file in oss failed:" + err.Error())
}
return true
}

70
oss_test.go Normal file
View File

@@ -0,0 +1,70 @@
package main
import (
"fmt"
"testing"
)
func TestPut(t *testing.T) {
ossConfig := &AliOssConfig{
EndPoint: "",
AccessKeyId: "",
AccessKeySecret: "",
BucketName: "",
}
client := ossConfig.CreateOssConnect()
uri := client.Put("logo/","./File/3HaqWaOzJWD86DDvZD9Pmn9VUEOBOBbuWackGOXb (2).jpeg")
fmt.Println(uri)
}
func TestExists(t *testing.T) {
ossConfig := &AliOssConfig{
EndPoint: "oss-cn-shenzhen.aliyuncs.com",
AccessKeyId: "",
AccessKeySecret: "",
BucketName: "",
}
client := ossConfig.CreateOssConnect()
isExists := client.HasExists("logo/a82bbd10-bb3f-5744-8843-5ef0d06c3b23.jpeg")
fmt.Println(isExists)
}
func TestDelete(t *testing.T) {
ossConfig := &AliOssConfig{
EndPoint: "oss-cn-shenzhen.aliyuncs.com",
AccessKeyId: "",
AccessKeySecret: "",
BucketName: "",
}
client := ossConfig.CreateOssConnect()
deleteRes := client.Delete("logo/41e6ddf4-fe9a-53c3-8994-0a69aba031c7.jpeg")
fmt.Println(deleteRes)
}
func TestAliOssClient_DeleteMore(t *testing.T) {
ossConfig := &AliOssConfig{
EndPoint: "oss-cn-shenzhen.aliyuncs.com",
AccessKeyId: "",
AccessKeySecret: "",
BucketName: "",
}
client := ossConfig.CreateOssConnect()
deleteRes := client.DeleteMore([]string{
"logo/b9f775db-8eb5-5652-86c9-5322ff4ba212.jpeg",
"logo/a82bbd10-bb3f-5744-8843-5ef0d06c3b23.jpeg",
})
fmt.Println(deleteRes)
}