/
cloudinary.go
82 lines (66 loc) · 1.92 KB
/
cloudinary.go
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
package helpers
import (
"context"
"log"
"mime/multipart"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"github.com/cloudinary/cloudinary-go/v2"
"github.com/cloudinary/cloudinary-go/v2/api/uploader"
"github.com/google/uuid"
)
var (
cld *cloudinary.Cloudinary
err error
)
func InitCloudinary() {
cloudName := os.Getenv("CLOUDINARY_CLOUD_NAME")
apiKey := os.Getenv("CLOUDINARY_API_KEY")
apiSecret := os.Getenv("CLOUDINARY_API_SECRET")
cld, err = cloudinary.NewFromParams(cloudName, apiKey, apiSecret)
if err != nil {
log.Fatal("error connecting to cloudinary:", err.Error())
}
log.Println("cloudinary connected successfully")
}
func publicIdPath(fileName string) string {
return "photos/" + fileName
}
func getFileNameFromUrl(fileUrlString string) string {
fileUrl, err := url.Parse(fileUrlString)
if err != nil {
log.Fatal(err)
}
// return last path from url
// example url: https://res.cloudinary.com/xxx/image/upload/yyy/photos/file-name.png"
// return value: file-name.png
fileNameWithExt := path.Base(fileUrl.Path)
// remove extension to get the file-name
// from 'file-name.png' to 'file-name'
return strings.TrimSuffix(fileNameWithExt, filepath.Ext(fileNameWithExt))
}
func UploadToCloudinary(file multipart.File) (string, error) {
ctx := context.Background()
fileName := uuid.New()
resp, err := cld.Upload.Upload(ctx, file, uploader.UploadParams{
PublicID: publicIdPath(fileName.String()), // folder-name/file-name
})
if err != nil {
log.Printf("error uploading file to cloudinary: %v", err.Error())
}
return resp.SecureURL, err
}
func DestroyFromCloudinary(fileUrlString string) (err error) {
ctx := context.Background()
fileName := getFileNameFromUrl(fileUrlString)
_, err = cld.Upload.Destroy(ctx, uploader.DestroyParams{
PublicID: publicIdPath(fileName),
})
if err != nil {
log.Printf("error trying to delete file '%v' from cloudinary: %v", fileUrlString, err.Error())
}
return
}