Skip to content

ServeStatic logic refactoring #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Nov 19, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
reworked serveStatic logic, different handler for File and Directory
  • Loading branch information
imwhocodes committed Nov 18, 2020
commit c428958a1e8b3523ad1a9ffc7fc9e06facdf3575
19 changes: 12 additions & 7 deletions libraries/ESP8266WebServer/src/ESP8266WebServer-impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -848,14 +848,19 @@ String ESP8266WebServerTemplate<ServerType>::responseCodeToString(const int code

template<typename ServerType>
void ESP8266WebServerETagTemplate<ServerType>::serveStatic(const char* uri, FS& fs, const char* path, const char* cache_header){
WST::_addRequestHandler(new StaticRequestETagHandler<ServerType>(fs, path, uri, cache_header));
}

bool is_file = false;

if (fs.exists(path)) {
File file = fs.open(path, "r");
is_file = file && file.isFile();
file.close();
}

// template<typename ServerType>
// void ESP8266WebServerETagTemplate<ServerType>::serveStatic(const char* uri, FS& fs, const char * path) {
// serveStatic(uri, fs, path, "");

// }
if(is_file)
WST::_addRequestHandler(new StaticFileRequestHandler<ServerType>(fs, path, uri, cache_header));
else
WST::_addRequestHandler(new StaticDirectoryRequestHandler<ServerType>(fs, path, uri, cache_header));
}

} // namespace
175 changes: 65 additions & 110 deletions libraries/ESP8266WebServer/src/detail/RequestHandlersImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,70 +72,82 @@ class StaticRequestHandler : public RequestHandler<ServerType> {
, _path(path)
, _cache_header(cache_header)
{
if (fs.exists(path)) {
File file = fs.open(path, "r");
_isFile = file && file.isFile();
file.close();
}
else {
_isFile = false;
}

DEBUGV("StaticRequestHandler: path=%s uri=%s isFile=%d, cache_header=%s\r\n", path, uri, _isFile, cache_header == __null ? "" : cache_header);
_baseUriLength = _uri.length();
}

bool canHandle(HTTPMethod requestMethod, const String& requestUri) override {
if ((requestMethod != HTTP_GET) && (requestMethod != HTTP_HEAD))
return false;
bool validMethod(HTTPMethod requestMethod){
return (requestMethod == HTTP_GET) || (requestMethod == HTTP_HEAD);
}

if ((_isFile && requestUri != _uri) || !requestUri.startsWith(_uri))
return false;
/* Deprecated version. Please use mime::getContentType instead */
static String getContentType(const String& path) __attribute__((deprecated)) {
return mime::getContentType(path);
}

return true;
protected:
FS _fs;
String _uri;
String _path;
String _cache_header;
};


template<typename ServerType>
class StaticDirectoryRequestHandler : public StaticRequestHandler<ServerType> {

using SRH = StaticRequestHandler<ServerType>;
using WebServerType = ESP8266WebServerTemplate<ServerType>;

public:
StaticDirectoryRequestHandler(FS& fs, const char* path, const char* uri, const char* cache_header)
:
SRH(fs, path, uri, cache_header),
_baseUriLength{SRH::_uri.length()}
{}

bool canHandle(HTTPMethod requestMethod, const String& requestUri) override {
return SRH::validMethod(requestMethod) && requestUri.startsWith(SRH::_uri);
}

bool handle(WebServerType& server, HTTPMethod requestMethod, const String& requestUri) override {

if (!canHandle(requestMethod, requestUri))
return false;

DEBUGV("StaticRequestHandler::handle: request=%s _uri=%s\r\n", requestUri.c_str(), _uri.c_str());
DEBUGV("DirectoryRequestHandler::handle: request=%s _uri=%s\r\n", requestUri.c_str(), SRH::_uri.c_str());

String path;
path.reserve(_path.length() + requestUri.length() + 32);
path = _path;

if (!_isFile) {
path.reserve(SRH::_path.length() + requestUri.length() + 32);
path = SRH::_path;

// Append whatever follows this URI in request to get the file path.
path += requestUri.substring(_baseUriLength);
// Append whatever follows this URI in request to get the file path.
path += requestUri.substring(_baseUriLength);

// Base URI doesn't point to a file.
// If a directory is requested, look for index file.
if (path.endsWith("/"))
path += F("index.htm");
// Base URI doesn't point to a file.
// If a directory is requested, look for index file.
if (path.endsWith("/"))
path += F("index.htm");

// If neither <blah> nor <blah>.gz exist, and <blah> is a file.htm, try it with file.html instead
// For the normal case this will give a search order of index.htm, index.htm.gz, index.html, index.html.gz
if (!_fs.exists(path) && !_fs.exists(path + ".gz") && path.endsWith(".htm")) {
path += 'l';
}
// If neither <blah> nor <blah>.gz exist, and <blah> is a file.htm, try it with file.html instead
// For the normal case this will give a search order of index.htm, index.htm.gz, index.html, index.html.gz
if (!SRH::_fs.exists(path) && !SRH::_fs.exists(path + ".gz") && path.endsWith(".htm")) {
path += 'l';
}
DEBUGV("StaticRequestHandler::handle: path=%s, isFile=%d\r\n", path.c_str(), _isFile);

DEBUGV("DirectoryRequestHandler::handle: path=%s\r\n", path.c_str());

String contentType = mime::getContentType(path);

using namespace mime;
// look for gz file, only if the original specified path is not a gz. So part only works to send gzip via content encoding when a non compressed is asked for
// if you point the the path to gzip you will serve the gzip as content type "application/x-gzip", not text or javascript etc...
if (!path.endsWith(FPSTR(mimeTable[gz].endsWith)) && !_fs.exists(path)) {
if (!path.endsWith(FPSTR(mimeTable[gz].endsWith)) && !SRH::_fs.exists(path)) {
String pathWithGz = path + FPSTR(mimeTable[gz].endsWith);
if(_fs.exists(pathWithGz))
if(SRH::_fs.exists(pathWithGz))
path += FPSTR(mimeTable[gz].endsWith);
}

File f = _fs.open(path, "r");
File f = SRH::_fs.open(path, "r");
if (!f)
return false;

Expand All @@ -144,66 +156,46 @@ class StaticRequestHandler : public RequestHandler<ServerType> {
return false;
}

if (_cache_header.length() != 0)
server.sendHeader("Cache-Control", _cache_header);
if (SRH::_cache_header.length() != 0)
server.sendHeader("Cache-Control", SRH::_cache_header);

server.streamFile(f, contentType, requestMethod);
return true;
}

/* Deprecated version. Please use mime::getContentType instead */
static String getContentType(const String& path) __attribute__((deprecated)) {
return mime::getContentType(path);
}

protected:
FS _fs;
String _uri;
String _path;
String _cache_header;
bool _isFile;
size_t _baseUriLength;
};

template<typename ServerType>
class StaticRequestETagHandler
class StaticFileRequestHandler
:
public StaticRequestHandler<ServerType> {

using SRH = StaticRequestHandler<ServerType>;

using WebServerType = ESP8266WebServerTemplate<ServerType>;

protected:
uint8_t _ETag_md5[16];

void computeMD5(File toHash){
public:
StaticFileRequestHandler(FS& fs, const char* path, const char* uri, const char* cache_header)
:
StaticRequestHandler<ServerType>{fs, path, uri, cache_header}
{
File f = SRH::_fs.open(path, "r");
MD5Builder calcMD5;
calcMD5.begin();
calcMD5.addStream(toHash, toHash.size());
calcMD5.addStream(f, f.size());
calcMD5.calculate();
calcMD5.getBytes(_ETag_md5);
f.close();
}


public:
StaticRequestETagHandler(FS& fs, const char* path, const char* uri, const char* cache_header)
:
StaticRequestHandler<ServerType>{fs, path, uri, cache_header}
{
File f = fs.open(path, "r");
if(f){
if(f.isFile())
computeMD5(f);
f.close();
}

bool canHandle(HTTPMethod requestMethod, const String& requestUri) override {
return SRH::validMethod(requestMethod) && requestUri == SRH::_uri;
}

bool handle(WebServerType& server, HTTPMethod requestMethod, const String & requestUri) override {
if (!SRH::canHandle(requestMethod, requestUri)){
if (!canHandle(requestMethod, requestUri))
return false;
}

const String etag = "\"" + base64::encode(_ETag_md5, 16, false) + "\"";

Expand All @@ -227,49 +219,12 @@ public StaticRequestHandler<ServerType> {

server.sendHeader("ETag", etag);


server.streamFile(f, SRH::getContentType(SRH::_path), requestMethod);
server.streamFile(f, mime::getContentType(SRH::_path), requestMethod);
return true;

}

// bool handle(WebServerType& server, HTTPMethod requestMethod, const String & requestUri) override {
// if (!SRH::canHandle(requestMethod, requestUri)){
// return false;
// }

// File f = SRH::_fs.open(SRH::_path, "r");

// if (!f)
// return false;

// if (!f.isFile()) {
// f.close();
// return false;
// }

// if(last_edit == f.getLastWrite()){
// //update chache
// }

// const String etag = "\"" + base64::encode(buff, 16, false) + "\"";

// if(server.header("If-None-Match") == etag){
// server.send(304);
// return true;
// }

// if (_cache_header.length() != 0)
// server.sendHeader("Cache-Control", SRH::_cache_header);

// server.sendHeader("ETag", etag);


// server.streamFile(f, SRH::getContentType(SRH::_path), requestMethod);
// return true;

// }

protected:
uint8_t _ETag_md5[16];
};

} // namespace
Expand Down