status code expressions: a simple way to match http status codes (go)

Published (click to see context) on 09/06/2022 by Morgan Bazalgette • 2 minutes

while working on a project, i found myself in need for a way to have simple expressions that could match to HTTP status codes, without necessarily using regexes. the idea is simple: have a list of status codes to accept, with placeholders, and maybe some exceptions.

my use case was creating a generic request entity which could perform webhook-type of requests to third party APIs (so retried if they fail), which could adapt to the way different APIs report permanent or temporary failure.

the result is a simple and performant ~100LOC set of functions which can easily create a function which matches codes intuitively. for instance: 4XX,5XX,!429 means match all codes from 400 to 599, except 429. and that’s pretty much all there is to the syntax, though of course the nitty-gritty is available on the godoc page. the time to parse the expression and execute the resulting function generally sits within 1-3 µs on modern hadware.

it is provided as a go command and not as a package as it is not meant to be included as a dependency: it’s only a hundred lines of code, and maybe you have some custom addition to add anyway which would only be cumbersome if you had to fork the project :)

source code: godoc:

#blogpost #golang