Skip to content

Commit 76d1170

Browse files
committed
Refactor AsyncFileResponse constructors
Eliminate the code duplication between the two forms by using a delegating constructor.
1 parent ceb1c26 commit 76d1170

File tree

1 file changed

+9
-32
lines changed

1 file changed

+9
-32
lines changed

src/WebResponses.cpp

Lines changed: 9 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -503,39 +503,16 @@ void AsyncFileResponse::_setContentType(const String& path){
503503
else _contentType = F("text/plain");
504504
}
505505

506-
AsyncFileResponse::AsyncFileResponse(FS &fs, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback): AsyncAbstractResponse(callback){
507-
_code = 200;
508-
_path = path;
509-
510-
if(!download && !fs.exists(_path) && fs.exists(_path+".gz")){
511-
_path = _path+".gz";
512-
addHeader(F("Content-Encoding"), F("gzip"));
513-
_callback = nullptr; // Unable to process zipped templates
514-
_sendContentLength = true;
515-
_chunked = false;
506+
static File fs_open_zipped(FS& fs, const String& path, bool force_absolute) {
507+
if (!force_absolute && !fs.exists(path)) {
508+
auto gz_path = path + F(".gz");
509+
if (fs.exists(gz_path)) return fs.open(gz_path, "r");
516510
}
511+
return fs.open(path, "r");
512+
};
517513

518-
_content = fs.open(_path, "r");
519-
_contentLength = _content.size();
520-
521-
if(contentType == "")
522-
_setContentType(path);
523-
else
524-
_contentType = contentType;
525-
526-
int filenameStart = path.lastIndexOf('/') + 1;
527-
char buf[26+path.length()-filenameStart];
528-
char* filename = (char*)path.c_str() + filenameStart;
529-
530-
if(download) {
531-
// set filename and force download
532-
snprintf_P(buf, sizeof (buf), PSTR("attachment; filename=\"%s\""), filename);
533-
} else {
534-
// force rendering
535-
snprintf_P(buf, sizeof (buf), PSTR("inline"));
536-
}
537-
addHeader(F("Content-Disposition"), buf);
538-
}
514+
AsyncFileResponse::AsyncFileResponse(FS &fs, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback)
515+
: AsyncFileResponse(fs_open_zipped(fs, path, download), path, contentType, download, callback) {};
539516

540517
AsyncFileResponse::AsyncFileResponse(File content, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback): AsyncAbstractResponse(callback){
541518
_code = 200;
@@ -551,7 +528,7 @@ AsyncFileResponse::AsyncFileResponse(File content, const String& path, const Str
551528
_content = content;
552529
_contentLength = _content.size();
553530

554-
if(contentType == "")
531+
if(contentType.length() == 0)
555532
_setContentType(path);
556533
else
557534
_contentType = contentType;

0 commit comments

Comments
 (0)