middleware and headers docs

This commit is contained in:
Joannis Orlandos 2017-09-11 11:51:56 +02:00
parent 193dfbc1cf
commit b639067bc1
2 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,48 @@
# Middleware
Middleware are a step in Vapor's responder chain. They're capable of modifying Requests/Responses, preventing the chain from continuing and transforming the data flow.
They can be employed for authorization checks, logging and a wide range of other functionalities.
## Implementing a Middleware
The following example is a middleware that will prevent all [requests](request.md) from going to their respective [responder](responder.md) unless the origin has a special header set. In the case of a missing header, [status code](status.md) 404 (not found) will be returned.
Don't secure your APIs using this example code, it's very unsafe and exclusively to be used as a test.
```swift
public final class SpecialHeaderCheckMiddleware: Middleware {
public func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> {
guard request.headers["Secret-Header"] == "MagicK3y" else {
return Response(status: .notFound)
}
return try next.respond(to: request)
}
}
```
## Intercepting/transforming Responses
The following example demonstrates a middleware that creates a session token for new users.
```swift
public final class SessionTokenMiddleware: Middleware {
func generateSessionToken() throws -> String {
// Generate token here ...
return token
}
public func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> {
let response = try next.respond(to: request)
guard request.cookies["session"] != nil else {
response.cookies["session"] = try generateSessionToken()
return response
}
return response
}
}
```

View File

@ -0,0 +1,51 @@
# Headers
HTTP Headers are the metadata of a request/response. They can provide a wide variety of information.
`Headers` are an array of key-value pairs. As such it's possible, but not common for multiple pairs to have the same key.
## Creating a Headers object
The most common syntax for creating Headers is a dictionary literal.
```swift
let headers: Headers = [
.contentType: "text/html"
]
```
The left hand side (key) is a `Header.Name`.
A name can also be initialized with a String literal.
```swift
let headers: Headers = [
"Content-Type": "text/html"
]
```
## Accessing headers
There are two ways to access Headers. Either by accessing a single (the first) value, or all values.
### A single value example:
```swift
let headers: Headers = [
.contentType: "text/html"
]
print(headers[.contentType]) // prints "text/html"
```
### Accessing all values example:
```swift
let headers: Headers = [
.setCookie: "session=afasfwrw3qr241j4qwmdsijfo13k43",
.setCookie: "awesome=true"
]
// prints ["session=afasfwrw3qr241j4qwmdsijfo13k43", "awesome=true"]
print(headers[valuesFor: .contentType])
```