Clear CloudFront cache in Golang

I'm streaming S3 images with CloudFront, but when I updated the images, I wanted to clear the cache (cache on the edge server), so I investigated how to do it.

Implement in Go

To implement in Golang, use the features around CloudFront in AWS SDK Go. The official is here: cloudfront --Amazon Web Services --Go SDK

Use the method CreateInvalidation in this SDK. The implementation looks like the following.

const (
	//CloudFront ID
	CloudFrontID = "HOGEHOGE"

	//Path to delete cache with cloudfront
	ClearTargetPath := "/*"
)

func ClearCache() error {
	svc := cloudfront.New(session.New())
	jstNow := time.Now().UTC().In(time.FixedZone("Asia/Tokyo", 9*60*60))
	callerReference := jstNow.Format("200601021504")

	_, err := svc.CreateInvalidation(createInvalidationInput(callerReference))
	if err != nil {
		return err
	}

	return nil
}

func createInvalidationInput(callerReference string) *cloudfront.CreateInvalidationInput {
	pathItems := []*string{&ClearTargetPath}

	return &cloudfront.CreateInvalidationInput{
		DistributionId: aws.String(CloudFrontID),
		InvalidationBatch: &cloudfront.InvalidationBatch{
			CallerReference: &callerReference,
			Paths: &cloudfront.Paths{
				Quantity: aws.Int64(1),
				Items:    pathItems,
			},
		},
	}
}

It seems that CallerReference should be a unique value, so I put a time stamp. Specify the DistributionId and path to be deleted with CreateInvalidationInput.

Don't forget to grant CloudFront permissions when running on Lambda.

Digression (How to delete from AWS web console)

It seems that the cache itself on CloudFront's edge server can also be cleared from the AWS web console. As you can see in [AWS] Amazon CloudFront Cache Invalidation, it is called ʻInvalidation`. Is the term that corresponds to cache deletion.

Recommended Posts

Clear CloudFront cache in Golang
Zero padding in Golang
Use HTTP cache in Python
Install GoLang in goenv of anyenv
Double quote csv elements in Golang