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
86
87
88
89
90
package main

import (
"context"
"fmt"
"net/url"
"os"
"strings"

cdn "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cdn/v20180606"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
"github.com/tencentyun/scf-go-lib/cloudevents/scf"
"github.com/tencentyun/scf-go-lib/cloudfunction"
)

var (
CDN_DOMAIN string = os.Getenv("CDN_DOMAIN")
TENCENTCLOUD_SECRET_ID string = os.Getenv("API_SECRET_ID")
TENCENTCLOUD_SECRET_KEY string = os.Getenv("API_SECRET_KEY")
commonCredentail *common.Credential
cdnClient *cdn.Client
)

func log(data ...interface{}) {
fmt.Println(data)
fmt.Println("---")
}

func recordsToUrls(records []scf.COSEventRecord) []*string {
url := make([]*string, 0)
for _, v := range records {
var cos scf.COSEntity = v.COS
var object scf.COSObject = cos.Object
var addr string = object.URL
url = append(url, &addr)
}
return url
}

func getCredential(secretId string, secretKey string) *common.Credential {
if commonCredentail == nil {
commonCredentail = common.NewCredential(secretId, secretKey)
}
return commonCredentail
}

func getCdnClient(credentail *common.Credential, region string) *cdn.Client {
if cdnClient == nil {
cpf := profile.NewClientProfile()
cdnClient, _ = cdn.NewClient(credentail, region, cpf)
}
return cdnClient
}

func purgeUrls(urls []*string) (string, error) {
credentail := getCredential(TENCENTCLOUD_SECRET_ID, TENCENTCLOUD_SECRET_KEY)
request := cdn.NewPurgeUrlsCacheRequest()
request.Urls = urls
client := getCdnClient(credentail, regions.Shanghai)
log(request.ToJsonString())
response, err := client.PurgeUrlsCache(request)
// 处理异常
if _, ok := err.(*errors.TencentCloudSDKError); ok {
log(err)
return "", err
}
return response.ToJsonString(), nil
}

func handler(ctx context.Context, evt scf.COSEvent) (string, error) {
var records []scf.COSEventRecord = evt.Records
urls := recordsToUrls(records)
for i, addr := range urls {
res, _ := url.Parse(*addr)
if strings.Contains(*addr, "upload") {
return "necessary", nil
}
url := strings.ReplaceAll(*addr, res.Host, CDN_DOMAIN)
urls[i] = &url
}
res, _ := purgeUrls(urls)
return res, nil
}

func main() {
cloudfunction.Start(handler)
}