golang 腾讯云 cos 上传文件 刷新 cdn

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)
}

相关文章

此处评论已关闭