Reputation: 37
Respected Seniors, I am using google storage bucket to store the static content of my website. I wanted this content to be cached in CDN, that is why I have made the bucket public, which results in setting https headers Cache-control to public and max-age to 3600 by default. I want to set max-age to higher value for all the future objects those will be uploaded in bucket. I have searched a lot but couldn't find any solution online. Please guide me if there is any way of doing that.
Upvotes: 1
Views: 973
Reputation: 1392
As explained in the documentation, the headers returned when accessing an object can be set modifying the metadata associated to it. There are two categories of metadata, one that's fixed and the other that is custom. The metadata/header Cache-Control is one of the fixed-key metadatas.
In the section about Cache-Control it is said that we can modify said header in order to modify the cache settings. If not provided, the value is set to public, max-age=3600
.
Using one public bucket of mine I have edited the Cache-Control to have the value public, max-age=5000
and when requesting the object the header was set with the correct value. Take a look at this guide in order to know how you can modify the metadata.
As explained in this answer, in order to automatically set the right header in the future objects of a bucket, a Cloud Function that uses the storage trigger finalize could be used so that it runs whenever an object gets uploaded/overwritten and changes the object's metadata.
from google.cloud import storage
CACHE_CONTROL = "public, max-age=3159200"
def set_cache_control_private(data, context):
print('Setting Cache-Control to {} for: gs://{}/{}'.format(CACHE_CONTROL, data['bucket'], data['name']))
storage_client = storage.Client()
bucket = storage_client.get_bucket(data['bucket'])
blob = bucket.get_blob(data['name'])
blob.cache_control = CACHE_CONTROL
blob.patch()
Notice how the code itself is almost the same as the other answer, but setting the Cache-Control to the new value that we decided.
Also the requirements.txt
file is needed with this content:
google-cloud-storage
Upvotes: 1