From 7b769fc2cb1738acd46416a64dd3ad0ca9aa4f5c Mon Sep 17 00:00:00 2001 From: Bogdan Popa Date: Thu, 31 Oct 2024 15:11:43 +0200 Subject: [PATCH] payload: add buffered-payload --- http-easy-lib/http-easy/private/payload.rkt | 17 +++++++++++++++++ http-easy-lib/info.rkt | 2 +- http-easy/http-easy.scrbl | 8 ++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/http-easy-lib/http-easy/private/payload.rkt b/http-easy-lib/http-easy/private/payload.rkt index a72c0e6..54047c5 100644 --- a/http-easy-lib/http-easy/private/payload.rkt +++ b/http-easy-lib/http-easy/private/payload.rkt @@ -15,11 +15,28 @@ (provide (contract-out + [buffered-payload (-> payload-procedure/c payload-procedure/c)] [form-payload (-> form-data/c payload-procedure/c)] [gzip-payload (-> payload-procedure/c payload-procedure/c)] [json-payload (-> jsexpr? payload-procedure/c)] [pure-payload (-> (or/c bytes? string? input-port?) payload-procedure/c)])) +(define ((buffered-payload p) hs) + (let*-values ([(hs data) (p hs)] + [(bs) + (cond + [(input-port? data) + (call-with-output-bytes + (lambda (out) + (copy-port data out)))] + [(string? data) + (string->bytes/utf-8 data)] + [else + data])]) + (define content-length + (number->string (bytes-length bs))) + (values (hash-set hs 'content-length content-length) bs))) + (define (form-payload v) (define data (alist->form-urlencoded v)) (lambda (hs) diff --git a/http-easy-lib/info.rkt b/http-easy-lib/info.rkt index 5ef28f4..08e0b44 100644 --- a/http-easy-lib/info.rkt +++ b/http-easy-lib/info.rkt @@ -1,7 +1,7 @@ #lang info (define license 'BSD-3-Clause) -(define version "0.7") +(define version "0.8") (define collection "net") (define deps '(["base" #:version "8.1.0.4"] diff --git a/http-easy/http-easy.scrbl b/http-easy/http-easy.scrbl index 9bf395f..7ec1eb6 100644 --- a/http-easy/http-easy.scrbl +++ b/http-easy/http-easy.scrbl @@ -675,6 +675,14 @@ sent to a remote server. value to be used as the request body. } +@defproc[(buffered-payload [p payload-procedure/c]) payload-procedure/c]{ + Produces a payload procedure that buffers the output of @racket[p] + in memory in order to determine its length before sending it to the + server. + + @history[#:added "0.8"] +} + @defproc[(form-payload [v form-data/c]) payload-procedure/c]{ Produces a payload procedure that encodes @racket[v] as form data using the @tt{application/x-www-form-urlencoded} content type.