[Varnish] 4.x Hit / Miss header

With version 4.x the classic snippet:

sub vcl_deliver {
        if (obj.hits > 0) {
                set resp.http.X-Cache = "HIT";
        } else {
                set resp.http.X-Cache = "MISS";
        }
}

doesn’t work anymore, because obj.hits no longer reports the number of hits for a cached object. In order to add a custom header indicating object origin, you must using a little trick with the X-Varnish header value.

A non-cachable or freshly added object will have only one hash. An object retrieved from the cache several hashed. This snippet use this property:

sub vcl_deliver {
  if (resp.http.X-Varnish ~ "[0-9]+ +[0-9]+") {
    set resp.http.X-Cache = "HIT";
  } else {
    set resp.http.X-Cache = "MISS";
  }
}