Allow "default" headers to be defined for all responses. (#230)

* Add DefaultHeaders singleton.

* Add documentation for DefaultHeaders.
This commit is contained in:
Greg Lincoln 2017-09-18 01:15:49 -04:00 committed by Me No Dev
parent b681dbc3cd
commit 46eebddd76
3 changed files with 58 additions and 2 deletions

View File

@ -77,7 +77,7 @@ To use this library you might need to have the latest git versions of [ESP32](ht
- [Setting up the server](#setting-up-the-server)
- [Setup global and class functions as request handlers](#setup-global-and-class-functions-as-request-handlers)
- [Methods for controlling websocket connections](#methods-for-controlling-websocket-connections)
- [Adding default headers to all responses](#adding-default-headers)
## Why should you care
- Using asynchronous network means that you can handle more than one connection at the same time
- You are called once the request is ready and parsed
@ -1339,3 +1339,30 @@ Example of OTA code
});
```
### Adding Default Headers
In some cases, such as when working with CORS, or with some sort of custom authentication system,
you might need to define a header that should get added to all responses (including static, websocket and EventSource).
The DefaultHeaders singleton allows you to do this.
Example:
```arduino
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
webServer.begin();
```
*NOTE*: You will still need to respond to the OPTIONS method for CORS pre-flight in most cases. (unless you are only using GET)
This is one option:
```arduino
webServer.onNotFound([](AsyncWebServerRequest *request) {
if (request->method() == HTTP_OPTIONS) {
request->send(200);
} else {
request->send(404);
}
});
```

View File

@ -414,6 +414,31 @@ class AsyncWebServer {
void _rewriteRequest(AsyncWebServerRequest *request);
};
class DefaultHeaders {
using headers_t = LinkedList<AsyncWebHeader *>;
headers_t _headers;
DefaultHeaders()
:_headers(headers_t([](AsyncWebHeader *h){ delete h; }))
{}
public:
using ConstIterator = headers_t::ConstIterator;
void addHeader(const String& name, const String& value){
_headers.add(new AsyncWebHeader(name, value));
}
ConstIterator begin() const { return _headers.begin(); }
ConstIterator end() const { return _headers.end(); }
DefaultHeaders(DefaultHeaders const &) = delete;
DefaultHeaders &operator=(DefaultHeaders const &) = delete;
static DefaultHeaders &Instance() {
static DefaultHeaders instance;
return instance;
}
};
#include "WebResponseImpl.h"
#include "WebHandlerImpl.h"
#include "AsyncWebSocket.h"

View File

@ -94,7 +94,11 @@ AsyncWebServerResponse::AsyncWebServerResponse()
, _ackedLength(0)
, _writtenLength(0)
, _state(RESPONSE_SETUP)
{}
{
for(auto header: DefaultHeaders::Instance()) {
_headers.add(new AsyncWebHeader(header->name(), header->value()));
}
}
AsyncWebServerResponse::~AsyncWebServerResponse(){
_headers.free();