Skip to content

Commit

Permalink
default to utf-8 if charset is invalid
Browse files Browse the repository at this point in the history
  • Loading branch information
pjfanning committed Aug 12, 2024
1 parent 38cceb3 commit e7fd945
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -283,11 +283,15 @@ class MarshallingDirectivesSpec extends RoutingSpec with Inside {
responseEntity shouldEqual HttpEntity(ContentType(`text/plain`, `UTF-8`), foo)
}
}
"rrender text with UTF-8 encoding if an `Accept-Charset` request header requests a non-UTF-8 encoding" in {
"render text with requested encoding if an `Accept-Charset` request header requests a non-UTF-8 encoding" in {
Get() ~> `Accept-Charset`(`ISO-8859-1`) ~> complete(foo) ~> check {
responseEntity shouldEqual HttpEntity(ContentType(`text/plain`, `ISO-8859-1`), foo)
}
}

"render text with UTF-8 encoding if an `Accept-Charset` request header requests an unknown encoding" in {
Get() ~> `Accept-Charset`(HttpCharset("unknown")(Nil)) ~> complete(foo) ~> check {
responseEntity shouldEqual HttpEntity(ContentType(`text/plain`, `UTF-8`), foo)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package org.apache.pekko.http.scaladsl.marshalling

import java.nio.CharBuffer
import java.nio.charset.UnsupportedCharsetException

import org.apache.pekko
import pekko.http.scaladsl.model.MediaTypes._
Expand Down Expand Up @@ -55,7 +56,17 @@ trait PredefinedToEntityMarshallers extends MultipartMarshallers {

implicit val StringMarshaller: ToEntityMarshaller[String] = stringMarshaller(`text/plain`)
def stringMarshaller(mediaType: MediaType.WithOpenCharset): ToEntityMarshaller[String] =
Marshaller.withOpenCharset(mediaType) { (s, cs) => HttpEntity(mediaType.withCharset(cs), s) }
Marshaller.withOpenCharset(mediaType) { (s, cs) =>
// https://github.com/apache/pekko-http/issues/300
// ignore issues with invalid charset - use UTF-8 instead
try {
HttpEntity(mediaType.withCharset(cs), s)
} catch {
case _: UnsupportedCharsetException =>
HttpEntity(mediaType.withCharset(HttpCharsets.`UTF-8`), s)
}

}
def stringMarshaller(mediaType: MediaType.WithFixedCharset): ToEntityMarshaller[String] =
Marshaller.withFixedContentType(mediaType) { s => HttpEntity(mediaType, s) }

Expand Down

0 comments on commit e7fd945

Please sign in to comment.