How to set a varnish response TTL dynamically

cachettlvarnish

my php script is sending a header X_Cache_ttl: 1h and in my varnish config file I have

sub vcl_fetch
{
    if(beresp.http.X-Cache-ttl){
            set beresp.ttl = beresp.http.X-Cache-ttl;
    }
}

but the line with the set command is causing varnish to fail when I try to start it.

in the log I get

Expression has type STRING, expected DURATION
('input' Line 116 Pos 34) -- ('input' Line 116 Pos 56)
            set beresp.ttl = beresp.http.X-Cache-ttl;

How do I convert X-Cache-ttl to a duration so that I can dynamically set the TTL?

I would like to avoid multiple if statements similar to

if(beresp.http.X-Cache-ttl == "60s") {
    set beresp.ttl = 60s;
}

if(beresp.http.X-Cache-ttl == "1h") {
    set beresp.ttl = 1h;
}

If it matters I'm using varnish 3.0.3 on centos 6.

Best Answer

The vmod_std module has a function that should do what you're looking for.

import std; at the top of the VCL, then this should work:

sub vcl_fetch
{
    set beresp.ttl = std.duration(beresp.http.X-Cache-ttl, 1h);
}

..where the 1h is your default if the header isn't set.

Related Topic