From 2a111f76ea9742ad78c5bc3f8f69c29e34ae1189 Mon Sep 17 00:00:00 2001 From: Daniel Vigovszky Date: Thu, 16 Mar 2023 10:33:58 +0100 Subject: [PATCH] Add content-type header based on endpoint body --- .../http/codec/internal/EncoderDecoder.scala | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/zio-http/src/main/scala/zio/http/codec/internal/EncoderDecoder.scala b/zio-http/src/main/scala/zio/http/codec/internal/EncoderDecoder.scala index 704315bb9e..d9e9dfaf40 100644 --- a/zio-http/src/main/scala/zio/http/codec/internal/EncoderDecoder.scala +++ b/zio-http/src/main/scala/zio/http/codec/internal/EncoderDecoder.scala @@ -128,14 +128,15 @@ private[codec] object EncoderDecoder { final def encodeWith[Z](value: Value)(f: (URL, Option[Status], Option[Method], Headers, Body) => Z): Z = { val inputs = deconstructor(value) - val path = encodePath(inputs.path) - val query = encodeQuery(inputs.query) - val status = encodeStatus(inputs.status) - val method = encodeMethod(inputs.method) - val headers = encodeHeaders(inputs.header) - val body = encodeBody(inputs.content) - - f(URL(path, queryParams = query), status, method, headers, body) + val path = encodePath(inputs.path) + val query = encodeQuery(inputs.query) + val status = encodeStatus(inputs.status) + val method = encodeMethod(inputs.method) + val headers = encodeHeaders(inputs.header) + val body = encodeBody(inputs.content) + val contentTypeHeaders = encodeContentType(inputs.content) + + f(URL(path, queryParams = query), status, method, headers ++ contentTypeHeaders, body) } private def decodePaths(path: Path, inputs: Array[Any]): Unit = { @@ -294,7 +295,7 @@ private[codec] object EncoderDecoder { } private def encodeHeaders(inputs: Array[Any]): Headers = { - var headers = Headers.contentType("application/json") + var headers = Headers.empty var i = 0 while (i < inputs.length) { @@ -327,5 +328,12 @@ private[codec] object EncoderDecoder { encoder(inputs(0)) } else throw new IllegalStateException("A request on a REST endpoint should have at most one body") } + + private def encodeContentType(inputs: Array[Any]): Headers = { + if (jsonEncoders.length == 0) Headers.empty + else if (jsonEncoders.length == 1) { + Headers.contentType(MediaType.application.json.fullType) + } else throw new IllegalStateException("A request on a REST endpoint should have at most one body") + } } }