swift-server / swift-server/async-http-client

support middlewares

Open
#393 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

kind/enhancement
Dominant language
Swift
Stars
1.1k
Forks
156
PR merge metrics
No merged PRs in 30d

Description

[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)
        }
    }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the linked three-tier library proposal in issue #392 and the existing HTTPService and client APIs. Use the authentication and redirect examples to clarify the middleware lifecycle and request-flow requirements. Done means an agreed middleware design that supports these use cases, rather than only the rough API sketch shown here.

Written by the indexing model from the issue text.

Assessment

Tech stack
swift
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.