Varnish变量和DRY代码



作为一名python工程师,学习编写DRY风格的代码;这并不是因为它是一个流行语,而是它让你的代码看起来更干净,其他人也能阅读。

任何一个读过前同事代码的人都能很好地理解这一点。

有了清漆,就没有变量赋值,所以怎么能尝试写DRY风格的规则呢?

考虑以下内容:

我有一个运行apache的后端实例集群,其中有十多个vhosts。有一个前端实例需要基于vhost进行重写。

我被这个卡住了:

if ( req.url ~ "^/amp/" ) {
    # vhost's AMP code == xyz
    if (req.http.host = "host1.com") {
       set req.url = regsub(req.url, "/amp/",  "/nps/$host1-brand-code/");
    }
     if (req.http.host = "host2.com") {
       set req.url = regsub(req.url, "/amp/",  "/nps/$host2-brand-code/");
    }
    ...
}

这里令人不安的是regsub 的重复

"/nps/$host1-brand-code/"

如果出版商决定下个月将其更改为/new-nps-url/$host1-brand-code,该怎么办。我将被迫为一个集群更新许多if语句,而我们有许多集群!

因此,如果你不想走vmod的路线(尽管@cory-shay建议的varvmod是一个很好的选择),一个选项是使用自定义子例程,然后使用HTTP变量像在Python中一样传递参数。

在您的情况下:

sub ourcompany_amp_code {
   set req.url = rebsub(req.url, "/amp/", "/nps/" + req.http.BRAND_CODE);
   // Cleanup so it does not get passed to upstream
   // Though the "_" in the name will generally prevent that
   // in any case
   unset req.http.BRAND_CODE;
}

sub vcl_recv {
     if (req.http.host = "host1.com") {
        set req.http.BRAND_CODE = "$host1-brand-code";
     } else if (req.http.host = "host2.com") {
        set req.http.BRAND_CODE = "$host2-brand-code";
     }
     call ourcompany_amp_code;
}

从理论上讲,这可以让你用品牌代码做很多事情。但是,如果你只想进行一次替换,你可以将ourcompany_amp_code的主体移动到你的一系列if语句之后。

使用var vmod,您可以简单地将req.http.BRAND_CODE的使用替换为var.set

最新更新