From 7795fa171d9fcab0fac02c71b2c3c66bbc3e19b1 Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Sat, 9 Nov 2019 17:35:54 +0100 Subject: [PATCH] Purge BunnyCDN 10 seconds after published --- bunnycdn.go | 18 ++++++++++++++++++ config.go | 9 +++++++++ main.go | 5 +++++ 3 files changed, 32 insertions(+) create mode 100644 bunnycdn.go diff --git a/bunnycdn.go b/bunnycdn.go new file mode 100644 index 0000000..7bead56 --- /dev/null +++ b/bunnycdn.go @@ -0,0 +1,18 @@ +package main + +import ( + "net/http" +) + +func Purge(url string) { + accessKey, err := GetBunnyCDNKey() + if err != nil || len(accessKey) == 0 { + return + } + client := &http.Client{} + req, _ := http.NewRequest("POST", "https://bunnycdn.com/api/purge?url="+url, nil) + req.Header.Add("Content-Type", "application/json") + req.Header.Add("Accept", "application/json") + req.Header.Add("AccessKey", accessKey) + _, _ = client.Do(req) +} diff --git a/config.go b/config.go index 500e29a..938b20f 100644 --- a/config.go +++ b/config.go @@ -28,3 +28,12 @@ func GetBlogURL() (string, error) { } return blogURL, nil } + + +func GetBunnyCDNKey() (string, error) { + bunnyCDNKey := os.Getenv("BUNNY_CDN_KEY") + if len(bunnyCDNKey) == 0 || bunnyCDNKey == "" { + return "", errors.New("BUNNY_CDN_KEY not specified") + } + return bunnyCDNKey, nil +} diff --git a/main.go b/main.go index a3cbed1..cd8d438 100644 --- a/main.go +++ b/main.go @@ -54,6 +54,11 @@ func handleMicroPub(w http.ResponseWriter, r *http.Request) { } else { w.Header().Add("Location", location) w.WriteHeader(http.StatusAccepted) + // Purge BunnyCDN in 10 seconds + go func() { + time.Sleep(10 * time.Second) + Purge(location) + }() return } } else {