Protocol
MultipartWriter
A protocol that defines the interface for writing multipart data.
protocol MultipartWriter<OutboundBody> : Sendable
Overview
Writers conforming to this protocol can serialize multipart data by writing boundaries, headers, and body chunks in the proper multipart format. The protocol supports both streaming and buffered writing approaches.
Implementing a Custom Writer
Only write(bytes:) has to be implemented. Boundaries, header fields, and whole parts are all written in terms of it by the default implementations, so a writer that sends a message somewhere is as small as this:
struct StdoutMultipartWriter: MultipartWriter {
typealias OutboundBody = [UInt8]
let boundary: String
func write(bytes: some Collection<UInt8> & Sendable) async throws {
print(String(decoding: bytes, as: UTF8.self), terminator: "")
}
}
// Usage example:
var writer = StdoutMultipartWriter(boundary: "boundary123")
try await writer.writeBoundary()
try await writer.writeHeaders([.contentType: "text/plain"])
try await writer.writeBodyChunk(Array("Hello, world!".utf8))
try await writer.finish()
Topics
Associated Types
associatedtype Failure : Error = NeverThe error the conforming writer will throw. Defaults toNever, i.e. the writer doesn’t throw.associatedtype OutboundBody : RangeReplaceableCollection, SendableThe type of the body element that the writer will produce.
Instance Properties
var boundary: StringBoundary string used to separate parts in the multipart data.
Instance Methods
func finish() async throws(Self.Failure)Writes the final boundary to the multipart data.func write(bytes: some Collection<UInt8> & Sendable) async throws(Self.Failure)Writes the given bytes to the multipart data.func writeBodyChunk(some RangeReplaceableCollection<UInt8> & Sendable) async throws(Self.Failure)Writes a single body chunk.func writeBodyChunks(_:)Writes multiple body chunks followed by a CRLF sequence.func writeBoundary(end: Bool) async throws(Self.Failure)Writes a multipart boundary with optional termination.func writeHeaders(HTTPFields) async throws(Self.Failure)Writes HTTP header fields for a multipart part.func writePart(MultipartPart<some RangeReplaceableCollection<UInt8> & Sendable>) async throws(Self.Failure)Writes a complete multipart part including boundary, headers, and body.
Relationships
Inherits From
Swift.SendableSwift.SendableMetatype