purge cloudflare cache in go

To purge Cloudflare cache in Go, you need to use Cloudflare API to send a request with purge command over HTTPS to Cloudflare's API endpoint. Here is an example code snippet that you can use to purge a single file from the Cloudflare cache:

main.go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

const (
	apiEndpoint = "https://api.cloudflare.com/client/v4"
	purgeURI    = "/zones/%s/purge_cache"
)

type PurgeCacheRequest struct {
	Files []string `json:"files"`
}

func main() {
	zoneID := "YOUR_ZONE_ID"
	apiKey := "YOUR_API_KEY"

	authHeaderValue := fmt.Sprintf("Bearer %s", apiKey)
	purgeURL := fmt.Sprintf(apiEndpoint+purgeURI, zoneID)

	req := PurgeCacheRequest{
		Files: []string{"https://example.com/file-to-purge"},
	}

	reqBodyReader := new(bytes.Buffer)
	json.NewEncoder(reqBodyReader).Encode(req)

	client := &http.Client{}
	r, _ := http.NewRequest("DELETE", purgeURL, reqBodyReader)
	r.Header.Add("Authorization", authHeaderValue)
	r.Header.Add("Content-Type", "application/json")

	resp, err := client.Do(r)
	if err != nil {
		fmt.Println(err)
		return
	}

	// check the response for success
	if resp.StatusCode != 200 {
		fmt.Printf("Unable to purge cache. Status code: %d\n", resp.StatusCode)
		return
	}

	fmt.Println("Cache has been purged!")
}
1038 chars
52 lines

This code will send a DELETE request to the Cloudflare API's purge_cache endpoint. You'll need to replace YOUR_ZONE_ID and YOUR_API_KEY with values from your Cloudflare account. You'll also need to specify the file(s) you want to purge from cache in the Files field of the PurgeCacheRequest struct.

Note that this is just an example of how to purge a single file from Cloudflare's cache. You may need to adjust this code depending on your specific requirements.

related categories

gistlibby LogSnag