Last active
November 7, 2019 16:56
-
-
Save rezan/1744e6d3dd3dad5eac668efef7458072 to your computer and use it in GitHub Desktop.
Varnish: validate JSON, if invalid, refetch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
varnishtest "Validate JSON, if invalid, refetch" | |
server s1 { | |
rxreq | |
txresp -hdr "Content-Type: application/json" -body { | |
{ | |
"some": "field", | |
"error...bad json | |
} | |
} | |
rxreq | |
txresp -hdr "Content-Type: application/json" -body { | |
{ | |
"some": "field", | |
"valid": true | |
} | |
} | |
} -start | |
varnish v1 -vcl+backend { | |
import edgestash; | |
import json; | |
sub vcl_recv { | |
# Should we attempt to refetch and reinsert a JSON request? | |
if (req.restarts > 0 && req.http.refetch-json) { | |
set req.hash_always_miss = true; | |
} | |
unset req.http.refetch-json; | |
} | |
sub vcl_backend_response { | |
# Setup JSON parsing | |
if (beresp.http.Content-Type ~ "json") { | |
edgestash.index_json(); | |
} | |
} | |
sub vcl_deliver { | |
# Do we have valid JSON? | |
if (resp.http.Content-Type ~ "json") { | |
json.parse_resp_index(); | |
# We don't, refetch | |
if (!json.is_valid()) { | |
set req.http.refetch-json = "true"; | |
return (restart); | |
} | |
set resp.http.json = json.is_object(); | |
} | |
} | |
} -start | |
client c1 { | |
txreq | |
rxresp | |
expect resp.status == 200 | |
expect resp.http.json == "true" | |
} -run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment