From 624cc7513a598cb54b799aef5846be7eb0b389e6 Mon Sep 17 00:00:00 2001 From: Emery Hemingway Date: Mon, 10 Jun 2024 17:02:49 +0300 Subject: [PATCH] http_client: content-type fixes --- src/http_client.nim | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/src/http_client.nim b/src/http_client.nim index 90ea44e..a695cf1 100644 --- a/src/http_client.nim +++ b/src/http_client.nim @@ -26,9 +26,30 @@ proc url(req: HttpRequest): Uri = elif i < vals.high: result.query.add ',' result.query.add val.string.encodeUrl -proc bodyString(req: HttpRequest): string = - if req.body.orKind == RequestBodyKind.present: - return cast[string](req.body.present) +proc toContent(body: Value; contentType: var string): string = + case contentType + of "application/json": + var stream = newStringStream() + writeText(stream, body, textJson) + return stream.data.move + of "application/preserves": + return cast[string](body.encode) + of "text/preserves": + return $body + else: + discard + + case body.kind + of pkString: + result = body.string + if contentType == "": + contentType = "text/plain" + of pkByteString: + result = cast[string](body.bytes) + if contentType == "": + contentType = "application/octet-stream" + else: + raise newException(ValueError, "unknown content type") proc spawnHttpClient*(turn: Turn; root: Cap): Actor {.discardable.} = @@ -42,14 +63,15 @@ proc spawnHttpClient*(turn: Turn; root: Cap): Actor {.discardable.} = headers = newHttpHeaders() contentType = "" for key, val in ctx.req.headers: - if key == Symbol"Content-Type": + if key == Symbol"content-type": contentType = val client.headers[key.string] = val let stdRes = client.request( ctx.req.url, ctx.req.method.string.toUpper, - ctx.req.bodyString, headers + ctx.req.body.toContent(contentType), headers ) + client.headers["content-type"] = contentType var resp = HttpResponse(orKind: HttpResponseKind.status) resp.status.code = stdRes.status[0 .. 2].parseInt resp.status.message = stdRes.status[3 .. ^1]