async-http-client icon indicating copy to clipboard operation
async-http-client copied to clipboard

support middlewares

Open weissi opened this issue 4 years ago • 2 comments

[initial suggestion from @Lukasa]

AHC should support a "middleware" concept (ideally once it's a "3-tier library") where a user can supply some middlewares which do common jobs like following redirects, authenticating requests, etc.

Very rough API sketch

final class AuthenticationMiddleware {
    // rough sketch, in reality returning just one modified request isn't good enough because with redirects we may
    // need more.
    func willPerformRequest(_ request: Request, http: HTTPService) -> EventLoopFuture<Request> {
        http.client().get("auth/produce/me/an/auth/token").map { token in
            var request = request
            request.headers[.authorization] = "bearer \(token)"
            return request
        }
    }
}


func makeTwoAuthenticatedHTTPRequests(http: HTTPService, eventLoop: EventLoop, logger: Logger) {
    let client = http.client(tlsConfiguration: ...,
                             eventLoop: eventLoop,
                             logger: logger,
                             middlewares: [AuthenticationMiddleware.self])

    return client.get("https://foo/bar").flatMap { first in
        client.get("https://bar/buz").flatMap { second in
            return (first, second)
        }
    }
}

weissi avatar Jul 07 '21 13:07 weissi

Service discovery could also be an idea for a middleware

weissi avatar Jul 07 '21 13:07 weissi

Further ideas for middlewares:

  • TLS cert rotations
  • Authentication to a service

weissi avatar Aug 15 '23 11:08 weissi