VCL: Fastly integer Math
Hi,
Is there a way to do simple math in fastly?
Example:
Received cookie = 10
New cookie to 10+8=18.
How can i declare an integer variable under req.http? I see that it allows only string variables to be declared.
-
You can (ab)use
req.grace
to do simple arithmetic:```
preserve req.grace
set req.http.VCL-grace = req.grace;
addition
set req.grace = 400s; set req.grace += 200s; set req.http.VCL-sum = req.grace; set req.http.VCL-sum = regsub(req.http.VCL-sum, "..*", "");
subtraction
set req.grace = 400s; set req.grace -= 200s; set req.http.VCL-difference = req.grace; set req.http.VCL-difference = regsub(req.http.VCL-difference, "..*", "");
multiplication
set req.grace = 400s; set req.grace = 200; set req.http.VCL-product = req.grace; set req.http.VCL-product = regsub(req.http.VCL-product, "..", "");
division
set req.grace = 400s; set req.grace /= 200; set req.http.VCL-quotient = req.grace; set req.http.VCL-quotient = regsub(req.http.VCL-quotient, "..*", "");
dynamic input
set req.http.X-Some-Input = "500"; set req.grace = std.atoi(req.http.X-Some-Input); set req.grace = 2; set req.http.VCL-product = req.grace; set req.http.VCL-product = regsub(req.http.VCL-product, "..", "");
time math
set req.grace = std.atoi(strftime({"%s"}, now)); set req.grace -= std.atoi(obj.entered); set http.X-Object-Entered-Cache-Unix = req.grace; set resp.http.X-Object-Entered-Cache-Unix = regsub(http.X-Object-Entered-Cache-Unix, "..*", "");
reset grace to its original value
set req.grace = std.atoi(req.http.VCL-grace); ```
If you need modulus you can use this formula:
dividend-((dividend/divisor)*divisor)
-
We recently added local variables to VCL, including numeric and time types, which make these kinds of calculations easy:
https://docs.fastly.com/guides/vcl/local-variables-in-vcl
Feel free to reach out if you have any questions.
Please sign in to leave a comment.
Comments
9 comments