http_client: content-type fixes

This commit is contained in:
Emery Hemingway 2024-06-10 17:02:49 +03:00
parent 6a4b34afcb
commit 624cc7513a
1 changed files with 27 additions and 5 deletions

View File

@ -26,9 +26,30 @@ proc url(req: HttpRequest): Uri =
elif i < vals.high: result.query.add ',' elif i < vals.high: result.query.add ','
result.query.add val.string.encodeUrl result.query.add val.string.encodeUrl
proc bodyString(req: HttpRequest): string = proc toContent(body: Value; contentType: var string): string =
if req.body.orKind == RequestBodyKind.present: case contentType
return cast[string](req.body.present) 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.} = proc spawnHttpClient*(turn: Turn; root: Cap): Actor {.discardable.} =
@ -42,14 +63,15 @@ proc spawnHttpClient*(turn: Turn; root: Cap): Actor {.discardable.} =
headers = newHttpHeaders() headers = newHttpHeaders()
contentType = "" contentType = ""
for key, val in ctx.req.headers: for key, val in ctx.req.headers:
if key == Symbol"Content-Type": if key == Symbol"content-type":
contentType = val contentType = val
client.headers[key.string] = val client.headers[key.string] = val
let stdRes = client.request( let stdRes = client.request(
ctx.req.url, ctx.req.url,
ctx.req.method.string.toUpper, 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) var resp = HttpResponse(orKind: HttpResponseKind.status)
resp.status.code = stdRes.status[0 .. 2].parseInt resp.status.code = stdRes.status[0 .. 2].parseInt
resp.status.message = stdRes.status[3 .. ^1] resp.status.message = stdRes.status[3 .. ^1]