How to write and call a subroutine in varnish

Subroutines are functions in varnish. To reuse a piece of code the subroutine is really handy in varnish.

Scenario:
Lets consider we need to extract a cookie value from varnish and store it into a http response header using a subroutine.

Subroutine: 
sub set_login {
    if(req.http.Cookie ~ "X-Cookie-Login") {
        set resp.http.X-Cookie-Login = regsub(req.http.Cookie, "^.*Login=", "");
        set resp.http.X-Cookie-Login = regsub(resp.http.X-Cookie-Login, ";.*", "");
        std.syslog(9, "Found::==>>>CookieValue: " + resp.http.X-Cookie-Login );
    } else {
          set resp.http.X-Cookie-Login = "";
    }
}

Explanation: 
In the http request cookie it looks for the cookie name "X-Cookie-Login". For success case it replaces everything from the beginning till Login=. Next line it replaces everything after the semicolon(;). Both the cases it stores the value in the http response header. In the third line it the extracted cookie value in the syslog.

In case of fail it writes empty string in the http response header.

Call subroutine:
call set_coupon_codes;

Comments