     }
 
     public func send(request: Request, middleware: Middleware...) throws -> Response {
-        let request = addHeaders(request)
-        return try middleware.intercept(self).respond(request)
+        var request = request
+        addHeaders(&request)
+        return try middleware.chain(to: self).respond(to: request)
     }
 
     private func send(request: Request, middleware: [Middleware]) throws -> Response {
-        let request = addHeaders(request)
-        return try middleware.intercept(self).respond(request)
+        var request = request
+        addHeaders(&request)
+        return try middleware.chain(to: self).respond(to: request)
     }
 }
 

@_exported import HTTPParser
@_exported import HTTPSerializer

public struct Client: Responder {
    public let host: String
    public let port: Int
    public let client: C7.StreamClient
    public let serializer: S4.RequestSerializer
    public let parser: S4.ResponseParser

    public init(host: String, port: Int, serializer: S4.RequestSerializer = RequestSerializer(), parser:S4.ResponseParser = ResponseParser()) throws {
        self.host = host
        self.port = port
        self.client = try TCPStreamClient(address: host, port: port)
        self.serializer = serializer
        self.parser = parser
    }
}

extension Client {
    private func addHeaders(request: Request) -> Request {
        var request = request
        request.host = "\(host):\(port)"
        request.userAgent = "Zewo"

        if request.connection == nil {
            request.connection = "close"
        }

        return request
    }

    public func respond(request: Request) throws -> Response {
        let request = addHeaders(request)
        let stream = try client.connect()

        try serializer.serialize(request) { data in
            try stream.send(data)
        }

        try stream.flush()

        while true {
            let data = try stream.receive()
            if let response = try parser.parse(data)  {

                if let upgrade = request.upgrade {
                    try upgrade(response, stream)
                }

                return response

        return try send(request, middleware: middleware)
    }
}



