HTTPMessageEncoder

public protocol HTTPMessageEncoder

Capable of encoding an Encodable type to an HTTPBody.

HTTPMessageEncoders may encode data into an HTTPBody using any of the available cases (streaming, static, or other).

let jsonEncoder: BodyEncoder = JSONEncoder()
let body = try jsonEncoder.encodeBody(from: "hello")
print(body) /// HTTPBody containing the string "hello"

The HTTPMessageEncoder protocol is what powers the ContentContainers on Request and Response.

try res.content.encode("hello", as: .plaintext)
print(res.mediaType) // .plaintext
print(res.http.body) // "hello"

HTTPMessageEncoders can be registered with ContentConfig during the application config phase. The encoders are associated with a MediaType when registered. When encoding content, the Content‘s default MediaType is used to lookup an appropriate coder. You can also choose to override the MediaType when encoding.

var contentConfig = ContentConfig.default()
contentConfig.use(encoder: JSONEncoder(), for: .json)
services.register(contentConfig)
  • Encodes the supplied Encodable object to an HTTPMessage.

    let jsonEncoder: HTTPMessageEncoder = JSONEncoder()
    let body = try jsonEncoder.encodeBody(from: "hello")
    print(body) /// HTTPBody containing the string "hello"
    

    Throws

    Any errors that may occur while encoding the object.

    Declaration

    Swift

    func encode<E, M>(_ encodable: E, to message: inout M, on worker: Worker) throws where E : Encodable, M : HTTPMessage

    Parameters

    from

    Encodable object that will be encoded to the HTTPMessage.

    Return Value

    Encoded HTTP body.