Skip to content

You're viewing documentation for a pre-release version. View the latest stable version

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

Instance Properties

Instance Methods

Relationships

Inherits From

  • Swift.Sendable
  • Swift.SendableMetatype

Conforming Types