我有一个蒸气应用程序,它需要执行通过HTTPS进行身份验证的大多数事情,但是还需要通过HTTP接收未经身份验证的PUT请求。
我是否可以基于服务器的主机名或身份验证类型来限定我的路由定义?如何从服务器捕获该信息?
if let index = env.arguments.index(of: "--hostname")
{
if env.arguments.count > index
{
let hostname = env.arguments[index+1]
if hostname == "hostA"
{
// load routes
}
else
{
// load other routes
}
}
}
一种替代方法是使用自定义Middleware
。这样可以检查请求中调用的主机名,并可以重定向禁止的路由:
struct HostSpecificMiddleware:Middleware
{
func respond( to request: Request, chainingTo next: Responder ) throws -> Future<Response>
{
let host = request.http.headers.filter{ (arg) in let (name, _) = arg; return name == "Host" }[0]
if host.1 == "hostA:8080"
{
if request.http.url.path == "routeA"
{
throw Abort.redirect(to:"routeNotAllowed")
}
}
return try next.respond(to: request)
}
}
然后您可以使用以下方法将中间件配置为configure.swift
中的路由:
let soMW = HostSpecificMiddleware()
let users = router.grouped(uriUsers).grouped(soMW)
第二种方法为您提供了更大的灵活性。