在 VCL 中使用 C 修改响应

Using C to modify response in VCL

varnish docs 说我们可以在 VCL 文件中包含 C 代码片段,例如

sub vcl_hash {
    C{
            int i = /* Some logic to get a number */
    }C
}

但现在如何使用整数 i 的值来设置响应 header 或 cookie

你为什么不直接使用 VCL? set resp.http.x-header = header 设置您想要设置的任何 header。

varnish.vcc

以及函数:

在 varnish 4 中为上下文定义了 ctx 变量(与 varnish 3 中的 sp 相对) (source)

示例:

sub vcl_hash {
    C{
        const char *hash = calc_hash(...);
        const struct gethdr_s hdr = { 
            HDR_BERESP,
            "0X-Hash:" // length prefixed string, in octal 
        };
        VRT_SetHdr(ctx, &hdr, hash, vrt_magic_string_end);
    }C
}

here for another example

我鼓励你直接写一个vmod,这样会更舒服。您可以在此处找到(旧但仍然相关的)指南:https://info.varnish-software.com/blog/creating-a-vmod-vmod-str