Skip to content

Instantly share code, notes, and snippets.

@kflu
Last active July 24, 2017 05:21
Show Gist options
  • Save kflu/81d0254ae688675d473a762b79f8748c to your computer and use it in GitHub Desktop.
Save kflu/81d0254ae688675d473a762b79f8748c to your computer and use it in GitHub Desktop.
parse http-status
#lang racket
(define-struct/contract http-status
([version string?]
[code (and/c positive? exact-integer?)]
[message string?])
#:transparent)
;; parse "HTTP/1.1 404 Not Found" into (http-status "HTTP/1.1" 404 "Not Found")
(define/contract (->http-status str)
(-> (or/c string? bytes?) (or/c #f http-status?))
(let* ([str (if (string? str) str (bytes->string/utf-8 str))]
[parsed (regexp-match #px"(.+) (\\d+) (.+)" str)])
(if [or (not parsed)
(not (list? parsed))
(not (= 4 (length parsed)))]
#f
(http-status (list-ref parsed 1)
(string->number (list-ref parsed 2))
(list-ref parsed 3)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment