« Back to Index

[Golang Fastly Purge by URL and by Key]

View original Gist on GitHub

Tags: #fastly #go #golang #purge #cdn #cache

Golang Fastly Purge by URL and by Key.go

// purgeByKey purges the Fastly edge cache by Surrogate-Key
func purgeByKey(key, testCase string, config *settings.Config) {
	serviceID := config.FastlyIDProd
	if config.Environment == "stage" {
		serviceID = config.FastlyIDStage
	}

	host := "https://api.fastly.com"
	path := fmt.Sprintf("/service/%s/purge/%s", serviceID, key)
	purgeURL := fmt.Sprintf("%s%s", host, path)

	req, err := http.NewRequest("POST", purgeURL, nil)
	if err != nil {
		msg := fmt.Sprintf("test - %s: failed to create new 'purge key' request", testCase)
		report(host, msg, err)
	}

	if config.Environment == "stage" {
		req.Header.Set("Fastly-Key", config.FastlyTokenStage)
	} else {
		req.Header.Set("Fastly-Key", config.FastlyTokenProd)
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		msg := fmt.Sprintf("test - %s: failed to make http 'purge key' request", testCase)
		report(host, msg, err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		msg := fmt.Sprintf("test - %s: failed to read 'purge key' response body", testCase)
		report(host, msg, err)
	}

	if config.Debug {
		fmt.Printf("\t'%s': %s\n\t\t%s", testCase, purgeURL, string(body))
	}
}

// purgeByURL purges the Fastly edge cache by URL
func purgeByURL(host, path, testCase string, config *settings.Config) {
	purgeURL := fmt.Sprintf("https://%s%s", host, path)

	req, err := http.NewRequest("PURGE", purgeURL, nil)
	if err != nil {
		msg := fmt.Sprintf("test - %s: failed to create new 'purge url' request", testCase)
		report(host, msg, err)
	}

	if config.Environment == "stage" {
		req.SetBasicAuth(config.BasicAuthUser, config.BasicAuthPass)

		// not all services use the same stage auth credentials
		if creds, ok := config.BasicAuthOverride[host]; ok {
			req.SetBasicAuth(creds["user"], creds["pass"])
		}
	}

	// headers required for purging Fastly's cached content
	if config.Environment == "stage" {
		req.Header.Set("Fastly-Key", config.FastlyTokenStage)
	} else {
		req.Header.Set("Fastly-Key", config.FastlyTokenProd)
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		msg := fmt.Sprintf("test - %s: failed to make http 'purge url' request", testCase)
		report(host, msg, err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		msg := fmt.Sprintf("test - %s: failed to read 'purge url' response body", testCase)
		report(host, msg, err)
	}

	if config.Debug {
		fmt.Printf("\t'%s': %s\n\t\t%s", testCase, purgeURL, string(body))
	}
}