|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "regexp" |
| 12 | + "strings" |
| 13 | +) |
| 14 | + |
| 15 | +const zoneID = "07b12080f7b57c1869b98fbceb028569" |
| 16 | + |
| 17 | +var authKey, authEmail string |
| 18 | + |
| 19 | +func init() { |
| 20 | + authKey = os.Getenv("CF_AUTH_KEY") |
| 21 | + if authKey == "" { |
| 22 | + fmt.Fprintln(os.Stderr, "set CF_AUTH_KEY (https://api.cloudflare.com/#getting-started-requests)") |
| 23 | + os.Exit(1) |
| 24 | + } |
| 25 | + authEmail = os.Getenv("CF_AUTH_EMAIL") |
| 26 | + if authEmail == "" { |
| 27 | + fmt.Fprintln(os.Stderr, "set CF_AUTH_EMAIL (https://api.cloudflare.com/#getting-started-requests)") |
| 28 | + os.Exit(1) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +func main() { |
| 33 | + pat := regexp.MustCompile(`'s3://(\S+)'`) |
| 34 | + a := make([]string, 0, 30) |
| 35 | + r := bufio.NewScanner(os.Stdin) |
| 36 | + for r.Scan() { |
| 37 | + f := pat.FindStringSubmatch(r.Text()) |
| 38 | + if len(f) == 0 { |
| 39 | + continue |
| 40 | + } |
| 41 | + url := f[1] |
| 42 | + if strings.HasSuffix(url, "/index.html") { |
| 43 | + url = strings.TrimSuffix(url, "index.html") |
| 44 | + } |
| 45 | + |
| 46 | + a = append(a, "https://" + url) |
| 47 | + |
| 48 | + if len(a) == 30 { |
| 49 | + purge(a) |
| 50 | + a = a[:0] |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if len(a) > 0 { |
| 55 | + purge(a) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +func purge(a []string) { |
| 60 | + fmt.Fprintln(os.Stderr, "purging", a) |
| 61 | + |
| 62 | + var in struct { |
| 63 | + Files []string `json:"files"` |
| 64 | + } |
| 65 | + in.Files = a |
| 66 | + |
| 67 | + b, err := json.Marshal(in) |
| 68 | + if err != nil { |
| 69 | + panic("couldn't encode json: " + err.Error()) |
| 70 | + } |
| 71 | + |
| 72 | + req, err := http.NewRequest( |
| 73 | + "POST", "https://api.cloudflare.com/client/v4/zones/"+zoneID+"/purge_cache", |
| 74 | + bytes.NewReader(b), |
| 75 | + ) |
| 76 | + if err != nil { |
| 77 | + panic("couldn't create request: " + err.Error()) |
| 78 | + } |
| 79 | + |
| 80 | + req.Header.Add("User-Agent", "foolish-cacheclear") |
| 81 | + req.Header.Add("Content-Type", "application/json") |
| 82 | + req.Header.Add("X-Auth-Key", authKey) |
| 83 | + req.Header.Add("X-Auth-Email", authEmail) |
| 84 | + |
| 85 | + resp, err := http.DefaultClient.Do(req) |
| 86 | + if err != nil { |
| 87 | + fmt.Fprintf(os.Stderr, "couldn't bust cache: %s\n", err) |
| 88 | + return |
| 89 | + } |
| 90 | + defer resp.Body.Close() |
| 91 | + |
| 92 | + if resp.StatusCode != 200 { |
| 93 | + fmt.Fprintln(os.Stderr, resp.Status) |
| 94 | + io.Copy(os.Stderr, resp.Body) |
| 95 | + } |
| 96 | +} |
0 commit comments