Search code examples
varnishvarnish-vcl

How to create custom function in default.vcl within Varnish?


I have repetitive code in my vcl and I want to create custom function without embedding inline C code. Is it possible?


Solution

  • You can define a custom subroutine like this

    sub my_subroutine {
      ... 
    }
    

    and call it like this:

    call my_subroutine;
    

    From: http://book.varnish-software.com/4.0/chapters/VCL_Basics.html

    Subroutines in VCL take neither arguments nor return values. Each subroutine terminates by calling return (action), where action is a keyword that indicates the desired outcome. Subroutines may inspect and manipulate HTTP header fields and various other aspects of each request. Subroutines instruct how requests are handled.

    Subroutine example:

    sub pipe_if_local { if (client.ip ~ local) { return (pipe); } }

    To call a subroutine, use the call keyword followed by the subroutine’s name:

    call pipe_if_local;

    Varnish has built-in subroutines that are hook into the Varnish workflow. These built-in subroutines are all named vcl_*. Your own subroutines cannot start their name with vcl_.