Skip to content

Commit

Permalink
add charsetWithUtf8Failover function
Browse files Browse the repository at this point in the history
  • Loading branch information
pjfanning committed Aug 16, 2024
1 parent 3ccd053 commit c8514e7
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,19 @@ final case class HttpCharset private[http] (override val value: String)(val alia
/** Returns the Charset for this charset if available or throws an exception otherwise */
def nioCharset: Charset = _nioCharset.get

/**
* @return this HttpCharset instance if this charset can be parsed to a
* <code>java.nio.charset.Charset</code> instance, otherwise returns the UTF-8 charset.
* @since 1.1.0
*/
def charsetWithUtf8Failover: HttpCharset = {
if (_nioCharset.isSuccess) {
this
} else {
HttpCharsets.`UTF-8`
}
}

private def readObject(in: java.io.ObjectInputStream): Unit = {
in.defaultReadObject()
_nioCharset = HttpCharset.findNioCharset(value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
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 All @@ -37,12 +36,7 @@ trait PredefinedToEntityMarshallers extends MultipartMarshallers {
Marshaller.withOpenCharset(mediaType) { (value, charset) =>
// https://github.com/apache/pekko-http/issues/300
// ignore issues with invalid charset - use UTF-8 instead
try {
marshalCharArray(value, mediaType.withCharset(charset))
} catch {
case _: UnsupportedCharsetException =>
marshalCharArray(value, mediaType.withCharset(HttpCharsets.`UTF-8`))
}
marshalCharArray(value, mediaType.withCharset(charset.charsetWithUtf8Failover))
}
def charArrayMarshaller(mediaType: MediaType.WithFixedCharset): ToEntityMarshaller[Array[Char]] =
Marshaller.withFixedContentType(mediaType) { value => marshalCharArray(value, mediaType) }
Expand All @@ -66,12 +60,7 @@ trait PredefinedToEntityMarshallers extends MultipartMarshallers {
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)
}
HttpEntity(mediaType.withCharset(cs.charsetWithUtf8Failover), s)
}
def stringMarshaller(mediaType: MediaType.WithFixedCharset): ToEntityMarshaller[String] =
Marshaller.withFixedContentType(mediaType) { s => HttpEntity(mediaType, s) }
Expand Down

0 comments on commit c8514e7

Please sign in to comment.