Search code examples
swiftvapor

Set hostname on HTTPRequest for testing


In writing tests for my Vapor 3 app, I've run into an issue where a certain framework is reliant on checking the incoming requests hostname

guard let peerHostName = request.http.remotePeer.hostname else {
            throw Abort(
                .forbidden,
                reason: "Unable to verify peer"
            )
        }

It would seem that when testing a request like below

let emails = (0...10).map { "email@test.co"}
let responder = try app.make(Responder.self)
let request = HTTPRequest(method: .POST, url: URL(string: "\(usersURI)/create")!, headers: headers)
let wrappedRequest = Request(http: request, using: app)
try wrappedRequest.content.encode(createUserReq)
try responder.respond(to: wrappedRequest)

Then the requests hostname is empty and thus an error is thrown. Is there any way I can manually set the hostname of the request? The hostname property is get only, so I can't set it that way


Solution

  • The solution was to add a 'forwarded' header

    var headers: HTTPHeaders = [
                "Content-Type": "application/json",
                "forwarded": "by=BY;for=127.0.0.1"
            ]