diff --git a/.clang-format b/.clang-format
new file mode 100644
index 000000000..8f4734879
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,246 @@
+# Clang format version: 18.1.3
+---
+BasedOnStyle: LLVM
+AccessModifierOffset: -2
+AlignAfterOpenBracket: BlockIndent
+AlignArrayOfStructures: None
+AlignConsecutiveAssignments:
+ Enabled: false
+ AcrossEmptyLines: false
+ AcrossComments: false
+ AlignCompound: false
+ AlignFunctionPointers: false
+ PadOperators: true
+AlignConsecutiveBitFields:
+ Enabled: true
+ AcrossEmptyLines: false
+ AcrossComments: false
+ AlignCompound: false
+ AlignFunctionPointers: false
+ PadOperators: false
+AlignConsecutiveDeclarations:
+ Enabled: false
+ AcrossEmptyLines: false
+ AcrossComments: false
+ AlignCompound: false
+ AlignFunctionPointers: false
+ PadOperators: false
+AlignConsecutiveMacros:
+ Enabled: true
+ AcrossEmptyLines: false
+ AcrossComments: false
+ AlignCompound: false
+ AlignFunctionPointers: false
+ PadOperators: false
+AlignConsecutiveShortCaseStatements:
+ Enabled: true
+ AcrossEmptyLines: false
+ AcrossComments: false
+ AlignCaseColons: false
+AlignEscapedNewlines: Left
+AlignOperands: Align
+AlignTrailingComments:
+ Kind: Always
+ OverEmptyLines: 0
+AllowAllArgumentsOnNextLine: true
+AllowAllParametersOfDeclarationOnNextLine: true
+AllowBreakBeforeNoexceptSpecifier: Never
+AllowShortBlocksOnASingleLine: Empty
+AllowShortCaseLabelsOnASingleLine: true
+AllowShortCompoundRequirementOnASingleLine: true
+AllowShortEnumsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: Empty
+AllowShortIfStatementsOnASingleLine: Never
+AllowShortLambdasOnASingleLine: Empty
+AllowShortLoopsOnASingleLine: true
+AlwaysBreakAfterDefinitionReturnType: None
+AlwaysBreakAfterReturnType: None
+AlwaysBreakBeforeMultilineStrings: false
+AlwaysBreakTemplateDeclarations: MultiLine
+AttributeMacros:
+ - __capability
+BinPackArguments: true
+BinPackParameters: true
+BitFieldColonSpacing: Both
+BraceWrapping:
+ AfterCaseLabel: true
+ AfterClass: false
+ AfterControlStatement: Never
+ AfterEnum: false
+ AfterFunction: false
+ AfterNamespace: false
+ AfterObjCDeclaration: false
+ AfterStruct: false
+ AfterUnion: false
+ AfterExternBlock: false
+ BeforeCatch: false
+ BeforeElse: false
+ BeforeLambdaBody: false
+ BeforeWhile: false
+ IndentBraces: false
+ SplitEmptyFunction: false
+ SplitEmptyRecord: true
+ SplitEmptyNamespace: true
+BreakAdjacentStringLiterals: true
+BreakAfterAttributes: Always
+BreakAfterJavaFieldAnnotations: false
+BreakArrays: false
+BreakBeforeBinaryOperators: NonAssignment
+BreakBeforeBraces: Custom
+BreakBeforeConceptDeclarations: Always
+BreakBeforeInlineASMColon: OnlyMultiline
+BreakBeforeTernaryOperators: true
+BreakConstructorInitializers: BeforeColon
+BreakInheritanceList: BeforeColon
+BreakStringLiterals: true
+ColumnLimit: 160
+CommentPragmas: ""
+CompactNamespaces: false
+ConstructorInitializerIndentWidth: 2
+ContinuationIndentWidth: 2
+Cpp11BracedListStyle: true
+DerivePointerAlignment: false
+DisableFormat: false
+EmptyLineAfterAccessModifier: Never
+EmptyLineBeforeAccessModifier: LogicalBlock
+ExperimentalAutoDetectBinPacking: false
+FixNamespaceComments: true
+ForEachMacros:
+ - foreach
+ - Q_FOREACH
+ - BOOST_FOREACH
+IfMacros:
+ - KJ_IF_MAYBE
+IncludeBlocks: Preserve
+IncludeCategories:
+ - Regex: ^"(llvm|llvm-c|clang|clang-c)/
+ Priority: 2
+ SortPriority: 0
+ CaseSensitive: false
+ - Regex: ^(<|"(gtest|gmock|isl|json)/)
+ Priority: 3
+ SortPriority: 0
+ CaseSensitive: false
+ - Regex: .*
+ Priority: 1
+ SortPriority: 0
+ CaseSensitive: false
+IncludeIsMainRegex: ""
+IncludeIsMainSourceRegex: ""
+IndentAccessModifiers: false
+IndentCaseBlocks: false
+IndentCaseLabels: true
+IndentExternBlock: NoIndent
+IndentGotoLabels: false
+IndentPPDirectives: None
+IndentRequiresClause: false
+IndentWidth: 2
+IndentWrappedFunctionNames: true
+InsertBraces: true
+InsertNewlineAtEOF: true
+InsertTrailingCommas: None
+IntegerLiteralSeparator:
+ Binary: 0
+ BinaryMinDigits: 0
+ Decimal: 0
+ DecimalMinDigits: 0
+ Hex: 0
+ HexMinDigits: 0
+JavaScriptQuotes: Leave
+JavaScriptWrapImports: true
+KeepEmptyLinesAtEOF: false
+KeepEmptyLinesAtTheStartOfBlocks: true
+LambdaBodyIndentation: Signature
+Language: Cpp
+LineEnding: LF
+MacroBlockBegin: ""
+MacroBlockEnd: ""
+MaxEmptyLinesToKeep: 1
+NamespaceIndentation: None
+ObjCBinPackProtocolList: Auto
+ObjCBlockIndentWidth: 2
+ObjCBreakBeforeNestedBlockParam: true
+ObjCSpaceAfterProperty: false
+ObjCSpaceBeforeProtocolList: true
+PPIndentWidth: -1
+PackConstructorInitializers: BinPack
+PenaltyBreakAssignment: 2
+PenaltyBreakBeforeFirstCallParameter: 19
+PenaltyBreakComment: 300
+PenaltyBreakFirstLessLess: 120
+PenaltyBreakOpenParenthesis: 0
+PenaltyBreakScopeResolution: 500
+PenaltyBreakString: 1000
+PenaltyBreakTemplateDeclaration: 10
+PenaltyExcessCharacter: 1000000
+PenaltyIndentedWhitespace: 0
+PenaltyReturnTypeOnItsOwnLine: 60
+PointerAlignment: Right
+QualifierAlignment: Leave
+ReferenceAlignment: Pointer
+ReflowComments: false
+RemoveBracesLLVM: false
+RemoveParentheses: Leave
+RemoveSemicolon: false
+RequiresClausePosition: OwnLine
+RequiresExpressionIndentation: OuterScope
+SeparateDefinitionBlocks: Leave
+ShortNamespaceLines: 1
+SkipMacroDefinitionBody: false
+SortIncludes: Never
+SortJavaStaticImport: Before
+SortUsingDeclarations: LexicographicNumeric
+SpaceAfterCStyleCast: false
+SpaceAfterLogicalNot: false
+SpaceAfterTemplateKeyword: false
+SpaceAroundPointerQualifiers: Default
+SpaceBeforeAssignmentOperators: true
+SpaceBeforeCaseColon: false
+SpaceBeforeCpp11BracedList: false
+SpaceBeforeCtorInitializerColon: true
+SpaceBeforeInheritanceColon: true
+SpaceBeforeJsonColon: false
+SpaceBeforeParens: ControlStatements
+SpaceBeforeParensOptions:
+ AfterControlStatements: true
+ AfterForeachMacros: true
+ AfterFunctionDeclarationName: false
+ AfterFunctionDefinitionName: false
+ AfterIfMacros: true
+ AfterOverloadedOperator: true
+ AfterPlacementOperator: true
+ AfterRequiresInClause: false
+ AfterRequiresInExpression: false
+ BeforeNonEmptyParentheses: false
+SpaceBeforeRangeBasedForLoopColon: true
+SpaceBeforeSquareBrackets: false
+SpaceInEmptyBlock: false
+SpacesBeforeTrailingComments: 2
+SpacesInAngles: Never
+SpacesInContainerLiterals: false
+SpacesInLineCommentPrefix:
+ Minimum: 1
+ Maximum: -1
+SpacesInParens: Never
+SpacesInParensOptions:
+ InConditionalStatements: false
+ InCStyleCasts: false
+ InEmptyParentheses: false
+ Other: false
+SpacesInSquareBrackets: false
+Standard: Auto
+StatementAttributeLikeMacros:
+ - Q_EMIT
+StatementMacros:
+ - Q_UNUSED
+ - QT_REQUIRE_VERSION
+TabWidth: 2
+UseTab: Never
+VerilogBreakBetweenInstancePorts: true
+WhitespaceSensitiveMacros:
+ - BOOST_PP_STRINGIZE
+ - CF_SWIFT_NAME
+ - NS_SWIFT_NAME
+ - PP_STRINGIZE
+ - STRINGIZE
+BracedInitializerIndentWidth: 2
diff --git a/.codespellrc b/.codespellrc
new file mode 100644
index 000000000..d26ee41f2
--- /dev/null
+++ b/.codespellrc
@@ -0,0 +1,8 @@
+[codespell]
+# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/spell-check/.codespellrc
+# In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here:
+ignore-words-list = ba,licence,varius
+skip = ./.git,./.licenses,__pycache__,.clang-format,.codespellrc,.editorconfig,.flake8,.prettierignore,.yamllint.yml,.gitignore
+builtin = clear,informal,en-GB_to_en-US
+check-filenames =
+check-hidden =
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 000000000..e22936cb1
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,60 @@
+# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/general/.editorconfig
+# See: https://editorconfig.org/
+# The formatting style defined in this file is the official standardized style to be used in all Arduino Tooling
+# projects and should not be modified.
+# Note: indent style for each file type is defined even when it matches the universal config in order to make it clear
+# that this type has an official style.
+
+[*]
+charset = utf-8
+end_of_line = lf
+indent_size = 2
+indent_style = space
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[*.{adoc,asc,asciidoc}]
+indent_size = 2
+indent_style = space
+
+[*.{bash,sh}]
+indent_size = 4
+indent_style = space
+
+[*.{c,cc,cp,cpp,cxx,h,hh,hpp,hxx,ii,inl,ino,ixx,pde,tpl,tpp,txx}]
+indent_size = 2
+indent_style = space
+
+[*.{go,mod}]
+indent_style = tab
+
+[*.java]
+indent_size = 2
+indent_style = space
+
+[*.{js,jsx,json,jsonc,json5,ts,tsx}]
+indent_size = 2
+indent_style = space
+
+[*.{md,mdx,mkdn,mdown,markdown}]
+indent_size = unset
+indent_style = space
+
+[*.proto]
+indent_size = 2
+indent_style = space
+
+[*.py]
+indent_size = 4
+indent_style = space
+
+[*.svg]
+indent_size = 2
+indent_style = space
+
+[*.{yaml,yml}]
+indent_size = 2
+indent_style = space
+
+[{.gitconfig,.gitmodules}]
+indent_style = tab
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 000000000..02f38c336
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,2 @@
+# https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository
+blank_issues_enabled: false
diff --git a/.github/ISSUE_TEMPLATE/issue-report.yml b/.github/ISSUE_TEMPLATE/issue-report.yml
new file mode 100644
index 000000000..d48e5ba4f
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/issue-report.yml
@@ -0,0 +1,91 @@
+name: 🐛 Bug Report
+description: File a bug report
+labels: ["Status: Awaiting triage"]
+body:
+ - type: markdown
+ attributes:
+ value: >
+ ### ⚠️ Please remember: issues are for *bugs* only!
+
+ - type: markdown
+ attributes:
+ value: |
+ #### Unsure? Have a questions? 👉 [Start a new discussion](https://github.com/ESP32Async/ESPAsyncWebServer/discussions/new)
+
+ #### Before opening a new issue, please make sure you have searched:
+
+ - In the [documentation](https://github.com/ESP32Async/ESPAsyncWebServer)
+ - In the [discussions](https://github.com/ESP32Async/ESPAsyncWebServer/discussions)
+ - In the [issues](https://github.com/ESP32Async/ESPAsyncWebServer/issues)
+ - In the [examples](https://github.com/ESP32Async/ESPAsyncWebServer/tree/main/examples)
+
+ #### Make sure you are using:
+
+ - The [latest version of ESPAsyncWebServer](https://github.com/ESP32Async/ESPAsyncWebServer/releases)
+ - The [latest version of AsyncTCP](https://github.com/ESP32Async/AsyncTCP/releases) (for ESP32)
+
+ - type: dropdown
+ id: platform
+ attributes:
+ label: Platform
+ options:
+ - ESP32
+ - ESP8266
+ - RP2040
+ validations:
+ required: true
+
+ - type: dropdown
+ id: tooling
+ attributes:
+ label: IDE / Tooling
+ options:
+ - Arduino (IDE/CLI)
+ - pioarduino
+ - ESP-IDF
+ - PlatformIO
+ validations:
+ required: true
+
+ - type: textarea
+ id: what-happened
+ attributes:
+ label: What happened?
+ description: A clear and concise description of the issue.
+ placeholder: A clear and concise description of the issue.
+ validations:
+ required: true
+
+ - type: textarea
+ id: stack-trace
+ attributes:
+ label: Stack Trace
+ description: Please provide a debug message or error message. If you have a Guru Meditation Error or Backtrace, [please decode it](https://maximeborges.github.io/esp-stacktrace-decoder/).
+ placeholder: For Arduino IDE, Enable Core debug level - Debug on tools menu, then put the serial output here.
+ validations:
+ required: true
+
+ - type: textarea
+ id: how-to-reproduce
+ attributes:
+ label: Minimal Reproductible Example (MRE)
+ description: Post the code or the steps to reproduce the issue.
+ placeholder: Post the code or the steps to reproduce the issue.
+ validations:
+ required: true
+
+ - type: checkboxes
+ id: confirmation
+ attributes:
+ label: "I confirm that:"
+ options:
+ - label: I have read the documentation.
+ required: true
+ - label: I have searched for similar discussions.
+ required: true
+ - label: I have searched for similar issues.
+ required: true
+ - label: I have looked at the examples.
+ required: true
+ - label: I have upgraded to the lasted version of ESPAsyncWebServer (and AsyncTCP for ESP32).
+ required: true
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 000000000..dfd0e3086
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,10 @@
+# Set update schedule for GitHub Actions
+
+version: 2
+updates:
+
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ # Check for updates to GitHub Actions every week
+ interval: "weekly"
diff --git a/.github/scripts/install-arduino-core-esp32.sh b/.github/scripts/install-arduino-core-esp32.sh
deleted file mode 100755
index 3fb4203c5..000000000
--- a/.github/scripts/install-arduino-core-esp32.sh
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/bin/bash
-
-export ARDUINO_ESP32_PATH="$ARDUINO_USR_PATH/hardware/espressif/esp32"
-if [ ! -d "$ARDUINO_ESP32_PATH" ]; then
- echo "Installing ESP32 Arduino Core ..."
- script_init_path="$PWD"
- mkdir -p "$ARDUINO_USR_PATH/hardware/espressif"
- cd "$ARDUINO_USR_PATH/hardware/espressif"
-
- echo "Installing Python Serial ..."
- pip3 install pyserial > /dev/null
-
- if [ "$OS_IS_WINDOWS" == "1" ]; then
- echo "Installing Python Requests ..."
- pip3 install requests > /dev/null
- fi
-
- if [ "$GITHUB_REPOSITORY" == "espressif/arduino-esp32" ]; then
- echo "Linking Core..."
- ln -s $GITHUB_WORKSPACE esp32
- else
- echo "Cloning Core Repository..."
- git clone https://github.com/espressif/arduino-esp32.git esp32 > /dev/null 2>&1
- fi
-
- echo "Updating Submodules ..."
- cd esp32
- git submodule update --init --recursive > /dev/null 2>&1
-
- echo "Installing Platform Tools ..."
- cd tools && python3 get.py
- cd $script_init_path
-
- echo "ESP32 Arduino has been installed in '$ARDUINO_ESP32_PATH'"
- echo ""
-fi
diff --git a/.github/scripts/install-arduino-core-esp8266.sh b/.github/scripts/install-arduino-core-esp8266.sh
deleted file mode 100644
index db9d56ca7..000000000
--- a/.github/scripts/install-arduino-core-esp8266.sh
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/bin/bash
-
-echo "Installing ESP8266 Arduino Core ..."
-script_init_path="$PWD"
-mkdir -p "$ARDUINO_USR_PATH/hardware/esp8266com"
-cd "$ARDUINO_USR_PATH/hardware/esp8266com"
-
-echo "Installing Python Serial ..."
-pip3 install pyserial > /dev/null
-
-if [ "$OS_IS_WINDOWS" == "1" ]; then
- echo "Installing Python Requests ..."
- pip3 install requests > /dev/null
-fi
-
-echo "Cloning Core Repository ..."
-git clone https://github.com/esp8266/Arduino.git esp8266 > /dev/null 2>&1
-
-echo "Updating submodules ..."
-cd esp8266
-git submodule update --init --recursive > /dev/null 2>&1
-
-echo "Installing Platform Tools ..."
-cd tools
-python3 get.py > /dev/null
-cd $script_init_path
-
-echo "ESP8266 Arduino has been installed in '$ARDUINO_USR_PATH/hardware/esp8266com'"
-echo ""
diff --git a/.github/scripts/install-arduino-ide.sh b/.github/scripts/install-arduino-ide.sh
deleted file mode 100755
index 584cc68dc..000000000
--- a/.github/scripts/install-arduino-ide.sh
+++ /dev/null
@@ -1,228 +0,0 @@
-#!/bin/bash
-
-#OSTYPE: 'linux-gnu', ARCH: 'x86_64' => linux64
-#OSTYPE: 'msys', ARCH: 'x86_64' => win32
-#OSTYPE: 'darwin18', ARCH: 'i386' => macos
-
-OSBITS=`arch`
-if [[ "$OSTYPE" == "linux"* ]]; then
- export OS_IS_LINUX="1"
- ARCHIVE_FORMAT="tar.xz"
- if [[ "$OSBITS" == "i686" ]]; then
- OS_NAME="linux32"
- elif [[ "$OSBITS" == "x86_64" ]]; then
- OS_NAME="linux64"
- elif [[ "$OSBITS" == "armv7l" || "$OSBITS" == "aarch64" ]]; then
- OS_NAME="linuxarm"
- else
- OS_NAME="$OSTYPE-$OSBITS"
- echo "Unknown OS '$OS_NAME'"
- exit 1
- fi
-elif [[ "$OSTYPE" == "darwin"* ]]; then
- export OS_IS_MACOS="1"
- ARCHIVE_FORMAT="zip"
- OS_NAME="macosx"
-elif [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then
- export OS_IS_WINDOWS="1"
- ARCHIVE_FORMAT="zip"
- OS_NAME="windows"
-else
- OS_NAME="$OSTYPE-$OSBITS"
- echo "Unknown OS '$OS_NAME'"
- exit 1
-fi
-export OS_NAME
-
-ARDUINO_BUILD_DIR="$HOME/.arduino/build.tmp"
-ARDUINO_CACHE_DIR="$HOME/.arduino/cache.tmp"
-
-if [ "$OS_IS_MACOS" == "1" ]; then
- export ARDUINO_IDE_PATH="/Applications/Arduino.app/Contents/Java"
- export ARDUINO_USR_PATH="$HOME/Documents/Arduino"
-elif [ "$OS_IS_WINDOWS" == "1" ]; then
- export ARDUINO_IDE_PATH="$HOME/arduino_ide"
- export ARDUINO_USR_PATH="$HOME/Documents/Arduino"
-else
- export ARDUINO_IDE_PATH="$HOME/arduino_ide"
- export ARDUINO_USR_PATH="$HOME/Arduino"
-fi
-
-if [ ! -d "$ARDUINO_IDE_PATH" ]; then
- echo "Installing Arduino IDE on $OS_NAME ..."
- echo "Downloading 'arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT' to 'arduino.$ARCHIVE_FORMAT' ..."
- if [ "$OS_IS_LINUX" == "1" ]; then
- wget -O "arduino.$ARCHIVE_FORMAT" "https://downloads.arduino.cc/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1
- echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..."
- tar xf "arduino.$ARCHIVE_FORMAT" > /dev/null
- mv arduino-nightly "$ARDUINO_IDE_PATH"
- else
- curl -o "arduino.$ARCHIVE_FORMAT" -L "https://downloads.arduino.cc/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1
- echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..."
- unzip "arduino.$ARCHIVE_FORMAT" > /dev/null
- if [ "$OS_IS_MACOS" == "1" ]; then
- mv "Arduino.app" "/Applications/Arduino.app"
- else
- mv arduino-nightly "$ARDUINO_IDE_PATH"
- fi
- fi
- rm -rf "arduino.$ARCHIVE_FORMAT"
-
- mkdir -p "$ARDUINO_USR_PATH/libraries"
- mkdir -p "$ARDUINO_USR_PATH/hardware"
-
- echo "Arduino IDE Installed in '$ARDUINO_IDE_PATH'"
- echo ""
-fi
-
-function build_sketch(){ # build_sketch [extra-options]
- if [ "$#" -lt 2 ]; then
- echo "ERROR: Illegal number of parameters"
- echo "USAGE: build_sketch [extra-options]"
- return 1
- fi
-
- local fqbn="$1"
- local sketch="$2"
- local build_flags="$3"
- local xtra_opts="$4"
- local win_opts=""
- if [ "$OS_IS_WINDOWS" == "1" ]; then
- local ctags_version=`ls "$ARDUINO_IDE_PATH/tools-builder/ctags/"`
- local preprocessor_version=`ls "$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/"`
- win_opts="-prefs=runtime.tools.ctags.path=$ARDUINO_IDE_PATH/tools-builder/ctags/$ctags_version -prefs=runtime.tools.arduino-preprocessor.path=$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/$preprocessor_version"
- fi
-
- echo ""
- echo "Compiling '"$(basename "$sketch")"' ..."
- mkdir -p "$ARDUINO_BUILD_DIR"
- mkdir -p "$ARDUINO_CACHE_DIR"
- $ARDUINO_IDE_PATH/arduino-builder -compile -logger=human -core-api-version=10810 \
- -fqbn=$fqbn \
- -warnings="all" \
- -tools "$ARDUINO_IDE_PATH/tools-builder" \
- -tools "$ARDUINO_IDE_PATH/tools" \
- -built-in-libraries "$ARDUINO_IDE_PATH/libraries" \
- -hardware "$ARDUINO_IDE_PATH/hardware" \
- -hardware "$ARDUINO_USR_PATH/hardware" \
- -libraries "$ARDUINO_USR_PATH/libraries" \
- -build-cache "$ARDUINO_CACHE_DIR" \
- -build-path "$ARDUINO_BUILD_DIR" \
- -prefs=compiler.cpp.extra_flags="$build_flags" \
- $win_opts $xtra_opts "$sketch"
-}
-
-function count_sketches() # count_sketches
-{
- local examples="$1"
- rm -rf sketches.txt
- if [ ! -d "$examples" ]; then
- touch sketches.txt
- return 0
- fi
- local sketches=$(find $examples -name *.ino)
- local sketchnum=0
- for sketch in $sketches; do
- local sketchdir=$(dirname $sketch)
- local sketchdirname=$(basename $sketchdir)
- local sketchname=$(basename $sketch)
- if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then
- continue
- fi;
- if [[ -f "$sketchdir/.test.skip" ]]; then
- continue
- fi
- echo $sketch >> sketches.txt
- sketchnum=$(($sketchnum + 1))
- done
- return $sketchnum
-}
-
-function build_sketches() # build_sketches [extra-options]
-{
- local fqbn=$1
- local examples=$2
- local chunk_idex=$3
- local chunks_num=$4
- local xtra_opts=$5
-
- if [ "$#" -lt 2 ]; then
- echo "ERROR: Illegal number of parameters"
- echo "USAGE: build_sketches [] [extra-options]"
- return 1
- fi
-
- if [ "$#" -lt 4 ]; then
- chunk_idex="0"
- chunks_num="1"
- xtra_opts=$3
- fi
-
- if [ "$chunks_num" -le 0 ]; then
- echo "ERROR: Chunks count must be positive number"
- return 1
- fi
- if [ "$chunk_idex" -ge "$chunks_num" ]; then
- echo "ERROR: Chunk index must be less than chunks count"
- return 1
- fi
-
- set +e
- count_sketches "$examples"
- local sketchcount=$?
- set -e
- local sketches=$(cat sketches.txt)
- rm -rf sketches.txt
-
- local chunk_size=$(( $sketchcount / $chunks_num ))
- local all_chunks=$(( $chunks_num * $chunk_size ))
- if [ "$all_chunks" -lt "$sketchcount" ]; then
- chunk_size=$(( $chunk_size + 1 ))
- fi
-
- local start_index=$(( $chunk_idex * $chunk_size ))
- if [ "$sketchcount" -le "$start_index" ]; then
- echo "Skipping job"
- return 0
- fi
-
- local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size ))
- if [ "$end_index" -gt "$sketchcount" ]; then
- end_index=$sketchcount
- fi
-
- local start_num=$(( $start_index + 1 ))
- echo "Found $sketchcount Sketches";
- echo "Chunk Count : $chunks_num"
- echo "Chunk Size : $chunk_size"
- echo "Start Sketch: $start_num"
- echo "End Sketch : $end_index"
-
- local sketchnum=0
- for sketch in $sketches; do
- local sketchdir=$(dirname $sketch)
- local sketchdirname=$(basename $sketchdir)
- local sketchname=$(basename $sketch)
- if [ "${sketchdirname}.ino" != "$sketchname" ] \
- || [ -f "$sketchdir/.test.skip" ]; then
- continue
- fi
- sketchnum=$(($sketchnum + 1))
- if [ "$sketchnum" -le "$start_index" ] \
- || [ "$sketchnum" -gt "$end_index" ]; then
- continue
- fi
- local sketchBuildFlags=""
- if [ -f "$sketchdir/.test.build_flags" ]; then
- while read line; do
- sketchBuildFlags="$sketchBuildFlags $line"
- done < "$sketchdir/.test.build_flags"
- fi
- build_sketch "$fqbn" "$sketch" "$sketchBuildFlags" "$xtra_opts"
- local result=$?
- if [ $result -ne 0 ]; then
- return $result
- fi
- done
- return 0
-}
diff --git a/.github/scripts/install-platformio.sh b/.github/scripts/install-platformio.sh
deleted file mode 100644
index 35b5f2de1..000000000
--- a/.github/scripts/install-platformio.sh
+++ /dev/null
@@ -1,140 +0,0 @@
-#!/bin/bash
-
-echo "Installing Python Wheel ..."
-pip3 install wheel > /dev/null 2>&1
-
-echo "Installing PlatformIO ..."
-pip3 install -U platformio > /dev/null 2>&1
-
-echo "PlatformIO has been installed"
-echo ""
-
-
-function build_pio_sketch(){ # build_pio_sketch
- if [ "$#" -lt 3 ]; then
- echo "ERROR: Illegal number of parameters"
- echo "USAGE: build_pio_sketch "
- return 1
- fi
-
- local board="$1"
- local sketch="$2"
- local buildFlags="$3"
- local sketch_dir=$(dirname "$sketch")
- echo ""
- echo "Compiling '"$(basename "$sketch")"' ..."
- python3 -m platformio ci -l '.' --board "$board" "$sketch_dir" --project-option="board_build.partitions = huge_app.csv" --project-option="build_flags=$buildFlags"
-}
-
-function count_sketches() # count_sketches
-{
- local examples="$1"
- rm -rf sketches.txt
- if [ ! -d "$examples" ]; then
- touch sketches.txt
- return 0
- fi
- local sketches=$(find $examples -name *.ino)
- local sketchnum=0
- for sketch in $sketches; do
- local sketchdir=$(dirname $sketch)
- local sketchdirname=$(basename $sketchdir)
- local sketchname=$(basename $sketch)
- if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then
- continue
- fi;
- if [[ -f "$sketchdir/.test.skip" ]]; then
- continue
- fi
- echo $sketch >> sketches.txt
- sketchnum=$(($sketchnum + 1))
- done
- return $sketchnum
-}
-
-function build_pio_sketches() # build_pio_sketches
-{
- if [ "$#" -lt 2 ]; then
- echo "ERROR: Illegal number of parameters"
- echo "USAGE: build_pio_sketches []"
- return 1
- fi
-
- local board=$1
- local examples=$2
- local chunk_idex=$3
- local chunks_num=$4
-
- if [ "$#" -lt 4 ]; then
- chunk_idex="0"
- chunks_num="1"
- fi
-
- if [ "$chunks_num" -le 0 ]; then
- echo "ERROR: Chunks count must be positive number"
- return 1
- fi
- if [ "$chunk_idex" -ge "$chunks_num" ]; then
- echo "ERROR: Chunk index must be less than chunks count"
- return 1
- fi
-
- set +e
- count_sketches "$examples"
- local sketchcount=$?
- set -e
- local sketches=$(cat sketches.txt)
- rm -rf sketches.txt
-
- local chunk_size=$(( $sketchcount / $chunks_num ))
- local all_chunks=$(( $chunks_num * $chunk_size ))
- if [ "$all_chunks" -lt "$sketchcount" ]; then
- chunk_size=$(( $chunk_size + 1 ))
- fi
-
- local start_index=$(( $chunk_idex * $chunk_size ))
- if [ "$sketchcount" -le "$start_index" ]; then
- echo "Skipping job"
- return 0
- fi
-
- local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size ))
- if [ "$end_index" -gt "$sketchcount" ]; then
- end_index=$sketchcount
- fi
-
- local start_num=$(( $start_index + 1 ))
- echo "Found $sketchcount Sketches";
- echo "Chunk Count : $chunks_num"
- echo "Chunk Size : $chunk_size"
- echo "Start Sketch: $start_num"
- echo "End Sketch : $end_index"
-
- local sketchnum=0
- for sketch in $sketches; do
- local sketchdir=$(dirname $sketch)
- local sketchdirname=$(basename $sketchdir)
- local sketchname=$(basename $sketch)
- if [ "${sketchdirname}.ino" != "$sketchname" ] \
- || [ -f "$sketchdir/.test.skip" ]; then
- continue
- fi
- local sketchBuildFlags=""
- if [ -f "$sketchdir/.test.build_flags" ]; then
- while read line; do
- sketchBuildFlags="$sketchBuildFlags $line"
- done < "$sketchdir/.test.build_flags"
- fi
- sketchnum=$(($sketchnum + 1))
- if [ "$sketchnum" -le "$start_index" ] \
- || [ "$sketchnum" -gt "$end_index" ]; then
- continue
- fi
- build_pio_sketch "$board" "$sketch" "$sketchBuildFlags"
- local result=$?
- if [ $result -ne 0 ]; then
- return $result
- fi
- done
- return 0
-}
diff --git a/.github/scripts/on-push.sh b/.github/scripts/on-push.sh
deleted file mode 100755
index 12a73a289..000000000
--- a/.github/scripts/on-push.sh
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/bin/bash
-
-set -e
-
-if [ ! -z "$TRAVIS_BUILD_DIR" ]; then
- export GITHUB_WORKSPACE="$TRAVIS_BUILD_DIR"
- export GITHUB_REPOSITORY="$TRAVIS_REPO_SLUG"
-elif [ -z "$GITHUB_WORKSPACE" ]; then
- export GITHUB_WORKSPACE="$PWD"
- export GITHUB_REPOSITORY="me-no-dev/ESPAsyncWebServer"
-fi
-
-TARGET_PLATFORM="$1"
-CHUNK_INDEX=$2
-CHUNKS_CNT=$3
-BUILD_PIO=0
-if [ "$#" -lt 1 ]; then
- TARGET_PLATFORM="esp32"
-fi
-if [ "$#" -lt 3 ] || [ "$CHUNKS_CNT" -le 0 ]; then
- CHUNK_INDEX=0
- CHUNKS_CNT=1
-elif [ "$CHUNK_INDEX" -gt "$CHUNKS_CNT" ]; then
- CHUNK_INDEX=$CHUNKS_CNT
-elif [ "$CHUNK_INDEX" -eq "$CHUNKS_CNT" ]; then
- BUILD_PIO=1
-fi
-
-if [ "$BUILD_PIO" -eq 0 ]; then
- # ArduinoIDE Test
- source ./.github/scripts/install-arduino-ide.sh
-
- echo "Installing ESPAsyncWebServer ..."
- cp -af "$GITHUB_WORKSPACE/src" "$ARDUINO_USR_PATH/libraries/ESPAsyncWebServer"
- echo "Installing ArduinoJson ..."
- git clone https://github.com/bblanchon/ArduinoJson "$ARDUINO_USR_PATH/libraries/ArduinoJson" > /dev/null 2>&1
-
- if [[ "$TARGET_PLATFORM" == "esp32" ]]; then
- echo "Installing AsyncTCP ..."
- git clone https://github.com/me-no-dev/AsyncTCP "$ARDUINO_USR_PATH/libraries/AsyncTCP" > /dev/null 2>&1
- FQBN="espressif:esp32:esp32:PSRAM=enabled,PartitionScheme=huge_app"
- source ./.github/scripts/install-arduino-core-esp32.sh
- echo "BUILDING ESP32 EXAMPLES"
- else
- echo "Installing ESPAsyncTCP ..."
- git clone https://github.com/me-no-dev/ESPAsyncTCP "$ARDUINO_USR_PATH/libraries/ESPAsyncTCP" > /dev/null 2>&1
- FQBN="esp8266com:esp8266:generic:eesz=4M1M,ip=lm2f"
- source ./.github/scripts/install-arduino-core-esp8266.sh
- echo "BUILDING ESP8266 EXAMPLES"
- fi
- build_sketches "$FQBN" "$GITHUB_WORKSPACE/examples" "$CHUNK_INDEX" "$CHUNKS_CNT"
-else
- # PlatformIO Test
- source ./.github/scripts/install-platformio.sh
-
- python3 -m platformio lib --storage-dir "$GITHUB_WORKSPACE" install
- echo "Installing ArduinoJson ..."
- python3 -m platformio lib -g install https://github.com/bblanchon/ArduinoJson.git > /dev/null 2>&1
- if [[ "$TARGET_PLATFORM" == "esp32" ]]; then
- BOARD="esp32dev"
- echo "Installing AsyncTCP ..."
- python3 -m platformio lib -g install https://github.com/me-no-dev/AsyncTCP.git > /dev/null 2>&1
- echo "BUILDING ESP32 EXAMPLES"
- else
- BOARD="esp12e"
- echo "Installing ESPAsyncTCP ..."
- python3 -m platformio lib -g install https://github.com/me-no-dev/ESPAsyncTCP.git > /dev/null 2>&1
- echo "BUILDING ESP8266 EXAMPLES"
- fi
- build_pio_sketches "$BOARD" "$GITHUB_WORKSPACE/examples"
-fi
diff --git a/.github/scripts/update-version.sh b/.github/scripts/update-version.sh
new file mode 100755
index 000000000..de8de77bc
--- /dev/null
+++ b/.github/scripts/update-version.sh
@@ -0,0 +1,40 @@
+
+#!/bin/bash
+# shellcheck disable=SC2002
+
+# fail the script if any command unexpectedly fails
+set -e
+
+if [ ! $# -eq 3 ]; then
+ echo "Bad number of arguments: $#" >&2
+ echo "usage: $0 " >&2
+ exit 1
+fi
+
+re='^[0-9]+$'
+if [[ ! $1 =~ $re ]] || [[ ! $2 =~ $re ]] || [[ ! $3 =~ $re ]] ; then
+ echo "error: Not a valid version: $1.$2.$3" >&2
+ echo "usage: $0 " >&2
+ exit 1
+fi
+
+ASYNCWEBSERVER_VERSION_MAJOR="$1"
+ASYNCWEBSERVER_VERSION_MINOR="$2"
+ASYNCWEBSERVER_VERSION_PATCH="$3"
+ASYNCWEBSERVER_VERSION="$ASYNCWEBSERVER_VERSION_MAJOR.$ASYNCWEBSERVER_VERSION_MINOR.$ASYNCWEBSERVER_VERSION_PATCH"
+
+echo "New AsyncTCP version: $ASYNCWEBSERVER_VERSION"
+
+echo "Updating library.properties..."
+cat library.properties | sed "s/version=.*/version=$ASYNCWEBSERVER_VERSION/g" > __library.properties && mv __library.properties library.properties
+
+echo "Updating library.json..."
+cat library.json | sed "s/^ \"version\":.*/ \"version\": \"$ASYNCWEBSERVER_VERSION\",/g" > __library.json && mv __library.json library.json
+
+echo "Updating src/AsyncWebServerVersion.h..."
+cat src/AsyncWebServerVersion.h | \
+sed "s/#define ASYNCWEBSERVER_VERSION_MAJOR.*/#define ASYNCWEBSERVER_VERSION_MAJOR $ASYNCWEBSERVER_VERSION_MAJOR/g" | \
+sed "s/#define ASYNCWEBSERVER_VERSION_MINOR.*/#define ASYNCWEBSERVER_VERSION_MINOR $ASYNCWEBSERVER_VERSION_MINOR/g" | \
+sed "s/#define ASYNCWEBSERVER_VERSION_PATCH.*/#define ASYNCWEBSERVER_VERSION_PATCH $ASYNCWEBSERVER_VERSION_PATCH/g" > src/__AsyncWebServerVersion.h && mv src/__AsyncWebServerVersion.h src/AsyncWebServerVersion.h
+
+exit 0
\ No newline at end of file
diff --git a/.github/stale.yml b/.github/stale.yml
deleted file mode 100644
index ce7a8e3f7..000000000
--- a/.github/stale.yml
+++ /dev/null
@@ -1,31 +0,0 @@
-# Configuration for probot-stale - https://github.com/probot/stale
-
-daysUntilStale: 60
-daysUntilClose: 14
-limitPerRun: 30
-staleLabel: stale
-exemptLabels:
- - pinned
- - security
- - "to be implemented"
- - "for reference"
- - "move to PR"
- - "enhancement"
-
-only: issues
-onlyLabels: []
-exemptProjects: false
-exemptMilestones: false
-exemptAssignees: false
-
-markComment: >
- [STALE_SET] This issue has been automatically marked as stale because it has not had
- recent activity. It will be closed in 14 days if no further activity occurs. Thank you
- for your contributions.
-
-unmarkComment: >
- [STALE_CLR] This issue has been removed from the stale queue. Please ensure activity to keep it openin the future.
-
-closeComment: >
- [STALE_DEL] This stale issue has been automatically closed. Thank you for your contributions.
-
diff --git a/.github/workflows/arduino-lint.yml b/.github/workflows/arduino-lint.yml
new file mode 100644
index 000000000..1abf11038
--- /dev/null
+++ b/.github/workflows/arduino-lint.yml
@@ -0,0 +1,25 @@
+# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
+
+name: Arduino Lint
+
+on:
+ workflow_dispatch:
+ push:
+ branches:
+ - main
+ - release/*
+ pull_request:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ arduino-lint:
+ name: Arduino Lint
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: arduino/arduino-lint-action@v2
+ with:
+ library-manager: update
diff --git a/.github/workflows/build-esp32.yml b/.github/workflows/build-esp32.yml
new file mode 100644
index 000000000..159e170a4
--- /dev/null
+++ b/.github/workflows/build-esp32.yml
@@ -0,0 +1,253 @@
+# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
+
+name: Build (ESP32)
+
+on:
+ workflow_dispatch:
+ push:
+ branches:
+ - main
+ - release/*
+ pull_request:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ arduino-esp32:
+ name: ESP32 (arduino-cli) - Release
+ runs-on: ubuntu-latest
+ steps:
+ - name: Install arduino-cli
+ run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh
+
+ - name: Update core index
+ run: arduino-cli core update-index --additional-urls https://espressif.github.io/arduino-esp32/package_esp32_index.json
+
+ - name: Install core
+ run: arduino-cli core install --additional-urls https://espressif.github.io/arduino-esp32/package_esp32_index.json esp32:esp32
+
+ - name: Install ArduinoJson
+ run: arduino-cli lib install ArduinoJson
+
+ - name: Install AsyncTCP (ESP32)
+ run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/ESP32Async/AsyncTCP#v3.4.5
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ arduino-cli compile --library . --warnings none -b esp32:esp32:esp32 "examples/$i/$i.ino"
+ done
+
+ arduino-esp32-dev:
+ name: ESP32 (arduino-cli) - Dev
+ runs-on: ubuntu-latest
+ steps:
+ - name: Install arduino-cli
+ run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh
+
+ - name: Update core index
+ run: arduino-cli core update-index --additional-urls https://espressif.github.io/arduino-esp32/package_esp32_dev_index.json
+
+ - name: Install core
+ run: arduino-cli core install --additional-urls https://espressif.github.io/arduino-esp32/package_esp32_dev_index.json esp32:esp32
+
+ - name: Install ArduinoJson
+ run: arduino-cli lib install ArduinoJson
+
+ - name: Install AsyncTCP (ESP32)
+ run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/ESP32Async/AsyncTCP#v3.4.5
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ arduino-cli compile --library . --warnings none -b esp32:esp32:esp32 "examples/$i/$i.ino"
+ done
+
+ platformio-esp32-arduino2:
+ name: ESP32 (pio) - Arduino 2
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ board:
+ - esp32dev
+ - esp32-s2-saola-1
+ - esp32-s3-devkitc-1
+ - esp32-c3-devkitc-02
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cache PlatformIO
+ uses: actions/cache@v4
+ with:
+ key: ${{ runner.os }}-pio
+ path: |
+ ~/.cache/pip
+ ~/.platformio
+
+ - name: Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install PIO
+ run: |
+ python -m pip install --upgrade pip
+ pip install --upgrade platformio
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ PLATFORMIO_SRC_DIR=examples/$i PIO_BOARD=${{ matrix.board }} pio run -e ci-arduino-2
+ done
+
+ platformio-esp32-arduino-3:
+ name: ESP32 (pio) - Arduino 3
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ board:
+ - esp32dev
+ - esp32-s2-saola-1
+ - esp32-s3-devkitc-1
+ - esp32-c3-devkitc-02
+ - esp32-c6-devkitc-1
+ - esp32-h2-devkitm-1
+ - esp32-p4
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cache PlatformIO
+ uses: actions/cache@v4
+ with:
+ key: ${{ runner.os }}-pio
+ path: |
+ ~/.cache/pip
+ ~/.platformio
+
+ - name: Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install PIO
+ run: |
+ python -m pip install --upgrade pip
+ pip install --upgrade platformio
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ PLATFORMIO_SRC_DIR=examples/$i PIO_BOARD=${{ matrix.board }} pio run -e ci-arduino-3
+ done
+
+ platformio-esp32-arduino-latest:
+ name: ESP32 (pio) - Arduino Latest
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ board:
+ - esp32dev
+ - esp32-s2-saola-1
+ - esp32-s3-devkitc-1
+ - esp32-c3-devkitc-02
+ - esp32-c6-devkitc-1
+ - esp32-h2-devkitm-1
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cache PlatformIO
+ uses: actions/cache@v4
+ with:
+ key: ${{ runner.os }}-pio
+ path: |
+ ~/.cache/pip
+ ~/.platformio
+
+ - name: Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install PIO
+ run: |
+ python -m pip install --upgrade pip
+ pip install --upgrade platformio
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ PLATFORMIO_SRC_DIR=examples/$i PIO_BOARD=${{ matrix.board }} pio run -e ci-arduino-3-latest
+ done
+
+ platformio-specific-envs:
+ name: ESP32 (pio) - Specific Envs
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ env:
+ - ci-arduino-3-latest-asynctcp
+ - ci-arduino-3-no-json
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cache PlatformIO
+ uses: actions/cache@v4
+ with:
+ key: ${{ runner.os }}-pio
+ path: |
+ ~/.cache/pip
+ ~/.platformio
+
+ - name: Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install PIO
+ run: |
+ python -m pip install --upgrade pip
+ pip install --upgrade platformio
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ PLATFORMIO_SRC_DIR=examples/$i PIO_BOARD=esp32dev pio run -e ${{ matrix.env }}
+ done
diff --git a/.github/workflows/build-esp8266.yml b/.github/workflows/build-esp8266.yml
new file mode 100644
index 000000000..1033769b7
--- /dev/null
+++ b/.github/workflows/build-esp8266.yml
@@ -0,0 +1,88 @@
+# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
+
+name: Build (8266)
+
+on:
+ workflow_dispatch:
+ push:
+ branches:
+ - main
+ - release/*
+ pull_request:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ arduino-esp8266:
+ name: ESP8266 (arduino-cli)
+ runs-on: ubuntu-latest
+ steps:
+ - name: Install arduino-cli
+ run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh
+
+ - name: Update core index
+ run: arduino-cli core update-index --additional-urls https://arduino.esp8266.com/stable/package_esp8266com_index.json
+
+ - name: Install core
+ run: arduino-cli core install --additional-urls https://arduino.esp8266.com/stable/package_esp8266com_index.json esp8266:esp8266
+
+ - name: Install ArduinoJson
+ run: arduino-cli lib install ArduinoJson
+
+ - name: Install ESPAsyncTCP (ESP8266)
+ run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/ESP32Async/ESPAsyncTCP#v2.0.0
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ arduino-cli compile --library . --warnings none -b esp8266:esp8266:huzzah "examples/$i/$i.ino"
+ done
+
+ platformio-esp8266:
+ name: ESP8266 (pio)
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ board:
+ - huzzah
+ - d1_mini
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cache PlatformIO
+ uses: actions/cache@v4
+ with:
+ key: ${{ runner.os }}-pio
+ path: |
+ ~/.cache/pip
+ ~/.platformio
+
+ - name: Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install PIO
+ run: |
+ python -m pip install --upgrade pip
+ pip install --upgrade platformio
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ PLATFORMIO_SRC_DIR=examples/$i PIO_BOARD=${{ matrix.board }} pio run -e ci-esp8266
+ done
diff --git a/.github/workflows/build-libretiny.yml b/.github/workflows/build-libretiny.yml
new file mode 100644
index 000000000..5e09bacbe
--- /dev/null
+++ b/.github/workflows/build-libretiny.yml
@@ -0,0 +1,57 @@
+# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
+
+name: Build (LibreTiny)
+
+on:
+ workflow_dispatch:
+ push:
+ branches:
+ - main
+ - release/*
+ pull_request:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ platformio-libretiny:
+ name: LibreTiny (pio)
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ board:
+ - generic-bk7231n-qfn32-tuya
+ - generic-rtl8710bn-2mb-788k
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cache PlatformIO
+ uses: actions/cache@v4
+ with:
+ key: ${{ runner.os }}-pio
+ path: |
+ ~/.cache/pip
+ ~/.platformio
+
+ - name: Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install PIO
+ run: |
+ python -m pip install --upgrade pip
+ pip install --upgrade platformio
+
+ - name: Build Examples
+ run: |
+ for i in AsyncResponseStream Auth Headers; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ PLATFORMIO_SRC_DIR=examples/$i PIO_BOARD=${{ matrix.board }} pio run -e ci-libretiny
+ done
diff --git a/.github/workflows/build-rpi.yml b/.github/workflows/build-rpi.yml
new file mode 100644
index 000000000..1efc4e501
--- /dev/null
+++ b/.github/workflows/build-rpi.yml
@@ -0,0 +1,95 @@
+# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
+
+name: Build (RPI)
+
+on:
+ workflow_dispatch:
+ push:
+ branches:
+ - main
+ - release/*
+ pull_request:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ arduino-rpi:
+ name: RPI (arduino-cli)
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ board:
+ - rpipicow
+ - rpipico2w
+
+ steps:
+ - name: Install arduino-cli
+ run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh
+
+ - name: Update core index
+ run: arduino-cli core update-index --additional-urls https://github.com/earlephilhower/arduino-pico/releases/download/4.4.4/package_rp2040_index.json
+
+ - name: Install core
+ run: arduino-cli core install --additional-urls https://github.com/earlephilhower/arduino-pico/releases/download/4.4.4/package_rp2040_index.json rp2040:rp2040
+
+ - name: Install ArduinoJson
+ run: arduino-cli lib install ArduinoJson
+
+ - name: Install RPAsyncTCP
+ run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/ayushsharma82/RPAsyncTCP#v1.3.2
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ arduino-cli compile --library . --warnings none -b rp2040:rp2040:${{ matrix.board }} "examples/$i/$i.ino"
+ done
+
+ platformio-rpi:
+ name: RPI (pio)
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ board:
+ - rpipicow
+ - rpipico2w
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cache PlatformIO
+ uses: actions/cache@v4
+ with:
+ key: ${{ runner.os }}-pio
+ path: |
+ ~/.cache/pip
+ ~/.platformio
+
+ - name: Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install PIO
+ run: |
+ python -m pip install --upgrade pip
+ pip install --upgrade platformio
+
+ - name: Build Examples
+ run: |
+ for i in `ls examples`; do
+ echo "============================================================="
+ echo "Building examples/$i..."
+ echo "============================================================="
+ PLATFORMIO_SRC_DIR=examples/$i PIO_BOARD=${{ matrix.board }} pio run -e ci-raspberrypi
+ done
diff --git a/.github/workflows/pre-commit-status.yml b/.github/workflows/pre-commit-status.yml
new file mode 100644
index 000000000..d00606684
--- /dev/null
+++ b/.github/workflows/pre-commit-status.yml
@@ -0,0 +1,64 @@
+# This needs to be in a separate workflow because it requires higher permissions than the calling workflow
+name: Report Pre-commit Check Status
+
+on:
+ workflow_run:
+ workflows: [Pre-commit hooks]
+ types:
+ - completed
+
+permissions:
+ statuses: write
+
+jobs:
+ report-success:
+ name: Report pre-commit success
+ if: github.event.workflow_run.conclusion == 'success'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Report success
+ uses: actions/github-script@v7
+ with:
+ script: |
+ const owner = '${{ github.repository_owner }}';
+ const repo = '${{ github.repository }}'.split('/')[1];
+ const sha = '${{ github.event.workflow_run.head_sha }}';
+ core.debug(`owner: ${owner}`);
+ core.debug(`repo: ${repo}`);
+ core.debug(`sha: ${sha}`);
+ const { context: name, state } = (await github.rest.repos.createCommitStatus({
+ context: 'Pre-commit checks',
+ description: 'Pre-commit checks successful',
+ owner: owner,
+ repo: repo,
+ sha: sha,
+ state: 'success',
+ target_url: 'https://github.com/${{ github.repository }}/actions/runs/${{ github.event.workflow_run.id }}'
+ })).data;
+ core.info(`${name} is ${state}`);
+
+ report-pending:
+ name: Report pre-commit pending
+ if: github.event.workflow_run.conclusion != 'success'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Report pending
+ uses: actions/github-script@v7
+ with:
+ script: |
+ const owner = '${{ github.repository_owner }}';
+ const repo = '${{ github.repository }}'.split('/')[1];
+ const sha = '${{ github.event.workflow_run.head_sha }}';
+ core.debug(`owner: ${owner}`);
+ core.debug(`repo: ${repo}`);
+ core.debug(`sha: ${sha}`);
+ const { context: name, state } = (await github.rest.repos.createCommitStatus({
+ context: 'Pre-commit checks',
+ description: 'The pre-commit checks need to be successful before merging',
+ owner: owner,
+ repo: repo,
+ sha: sha,
+ state: 'pending',
+ target_url: 'https://github.com/${{ github.repository }}/actions/runs/${{ github.event.workflow_run.id }}'
+ })).data;
+ core.info(`${name} is ${state}`);
diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml
new file mode 100644
index 000000000..b92f283d1
--- /dev/null
+++ b/.github/workflows/pre-commit.yml
@@ -0,0 +1,80 @@
+name: Pre-commit hooks
+
+on:
+ workflow_dispatch:
+ push:
+ branches:
+ - main
+ pull_request:
+ types: [opened, reopened, synchronize, labeled]
+
+concurrency:
+ group: pre-commit-${{github.event.pull_request.number || github.ref}}
+ cancel-in-progress: true
+
+jobs:
+ lint:
+ if: |
+ github.event_name != 'pull_request' ||
+ contains(github.event.pull_request.labels.*.name, 'Status: Pending Merge') ||
+ contains(github.event.pull_request.labels.*.name, 'Re-trigger Pre-commit')
+
+ name: Check if fixes are needed
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout latest commit
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 2
+
+ - name: Remove Label
+ if: contains(github.event.pull_request.labels.*.name, 'Re-trigger Pre-commit')
+ run: gh pr edit ${{ github.event.number }} --remove-label 'Re-trigger Pre-commit'
+ env:
+ GH_TOKEN: ${{ github.token }}
+
+ - name: Set up Python 3
+ uses: actions/setup-python@v5
+ with:
+ cache-dependency-path: pre-commit.requirements.txt
+ cache: "pip"
+ python-version: "3.x"
+
+ - name: Get Python version hash
+ run: |
+ echo "Using $(python -VV)"
+ echo "PY_HASH=$(python -VV | sha256sum | cut -d' ' -f1)" >> $GITHUB_ENV
+
+ - name: Restore pre-commit cache
+ uses: actions/cache/restore@v4
+ id: restore-cache
+ with:
+ path: |
+ ~/.cache/pre-commit
+ key: pre-commit-${{ env.PY_HASH }}-${{ hashFiles('.pre-commit-config.yaml', '.github/workflows/pre-commit.yml', 'pre-commit.requirements.txt') }}
+
+ - name: Install python dependencies
+ run: python -m pip install -r pre-commit.requirements.txt
+
+ - name: Get changed files
+ id: changed-files
+ uses: tj-actions/changed-files@v42.0.2
+
+ - name: Run pre-commit hooks in changed files
+ run: pre-commit run --color=always --show-diff-on-failure --files ${{ steps.changed-files.outputs.all_changed_files }}
+
+ - name: Save pre-commit cache
+ uses: actions/cache/save@v4
+ if: ${{ always() && steps.restore-cache.outputs.cache-hit != 'true' }}
+ continue-on-error: true
+ with:
+ path: |
+ ~/.cache/pre-commit
+ key: ${{ steps.restore-cache.outputs.cache-primary-key }}
+
+ - name: Push changes using pre-commit-ci-lite
+ uses: pre-commit-ci/lite-action@v1.1.0
+ # Only push changes in PRs
+ if: ${{ always() && github.event_name == 'pull_request' }}
+ with:
+ msg: "ci(pre-commit): Apply automatic fixes"
diff --git a/.github/workflows/publish-pio-registry.yml b/.github/workflows/publish-pio-registry.yml
new file mode 100644
index 000000000..2961c7b1f
--- /dev/null
+++ b/.github/workflows/publish-pio-registry.yml
@@ -0,0 +1,62 @@
+# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
+
+name: Publish to PlatformIO
+
+on:
+ workflow_dispatch:
+ inputs:
+ tag_name:
+ description: "Tag name of the release to publish (use 'latest' for the most recent tag)"
+ required: true
+ default: "latest"
+
+jobs:
+ publish:
+ name: Publish
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-tags: true
+ fetch-depth: 0 # Ensure all commits and tags are fetched
+
+ - name: Show latest tag
+ run: git tag --sort=-creatordate | head -n 1
+
+ - name: Download release zip
+ run: |
+ if [ "${{ inputs.tag_name }}" == "latest" ]; then
+ TAG_NAME=$(git tag --sort=-creatordate | head -n 1)
+ if [ -z "$TAG_NAME" ]; then
+ echo "Error: No tags found in the repository."
+ exit 1
+ fi
+ else
+ TAG_NAME="${{ inputs.tag_name }}"
+ fi
+ echo "Downloading tag: $TAG_NAME"
+ curl -L -o project.zip "https://github.com/${{ github.repository }}/archive/refs/tags/$TAG_NAME.zip"
+
+ - name: Cache PlatformIO
+ uses: actions/cache@v4
+ with:
+ key: ${{ runner.os }}-pio
+ path: |
+ ~/.cache/pip
+ ~/.platformio
+
+ - name: Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install PlatformIO CLI
+ run: |
+ python -m pip install --upgrade pip
+ pip install --upgrade platformio
+
+ - name: Publish to PlatformIO
+ run: pio pkg publish --no-interactive --owner ${{ github.repository_owner }} project.zip
+ env:
+ PLATFORMIO_AUTH_TOKEN: ${{ secrets.PLATFORMIO_AUTH_TOKEN }}
diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml
deleted file mode 100644
index 50d62e167..000000000
--- a/.github/workflows/push.yml
+++ /dev/null
@@ -1,36 +0,0 @@
-name: ESP Async Web Server CI
-
-on:
- push:
- branches:
- - master
- - release/*
- pull_request:
-
-jobs:
-
- build-arduino:
- name: Arduino for ${{ matrix.board }} on ${{ matrix.os }}
- runs-on: ${{ matrix.os }}
- strategy:
- fail-fast: false
- matrix:
- os: [ubuntu-latest, windows-latest, macOS-latest]
- board: [esp32, esp8266]
- steps:
- - uses: actions/checkout@v3.0.2
- - name: Build Tests
- run: bash ./.github/scripts/on-push.sh ${{ matrix.board }} 0 1
-
- build-pio:
- name: PlatformIO for ${{ matrix.board }} on ${{ matrix.os }}
- runs-on: ${{ matrix.os }}
- strategy:
- fail-fast: false
- matrix:
- os: [ubuntu-latest, windows-latest, macOS-latest]
- board: [esp32, esp8266]
- steps:
- - uses: actions/checkout@v3.0.2
- - name: Build Tests
- run: bash ./.github/scripts/on-push.sh ${{ matrix.board }} 1 1
diff --git a/.github/workflows/stale.yaml b/.github/workflows/stale.yaml
new file mode 100644
index 000000000..14ceb43c2
--- /dev/null
+++ b/.github/workflows/stale.yaml
@@ -0,0 +1,24 @@
+name: "Close stale issues and PRs"
+on:
+ schedule:
+ - cron: "30 1 * * *"
+
+jobs:
+ stale:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/stale@v9
+ with:
+ stale-issue-message: "This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days."
+ stale-pr-message: "This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days."
+ close-issue-message: "This issue was closed because it has been stalled for 7 days with no activity."
+ close-pr-message: "This PR was closed because it has been stalled for 7 days with no activity."
+ days-before-issue-stale: 30
+ days-before-pr-stale: 30
+ days-before-issue-close: 7
+ days-before-pr-close: 7
+
+permissions:
+ # contents: write # only for delete-branch option
+ issues: write
+ pull-requests: write
diff --git a/.github/workflows/upload-idf-component.yml b/.github/workflows/upload-idf-component.yml
new file mode 100644
index 000000000..e68384b83
--- /dev/null
+++ b/.github/workflows/upload-idf-component.yml
@@ -0,0 +1,50 @@
+name: Publish ESP-IDF Component
+
+on:
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: 'Component version (1.2.3, 1.2.3-rc1 or 1.2.3.4)'
+ required: true
+ git_ref:
+ description: 'Git ref with the source (branch, tag or commit)'
+ required: true
+
+permissions:
+ contents: read
+
+jobs:
+ upload_components:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Get the release tag
+ env:
+ head_branch: ${{ inputs.tag || github.event.workflow_run.head_branch }}
+ run: |
+ # Read and sanitize the branch/tag name
+ branch=$(echo "$head_branch" | tr -cd '[:alnum:]/_.-')
+
+ if [[ $branch == refs/tags/* ]]; then
+ tag="${branch#refs/tags/}"
+ elif [[ $branch =~ ^[v]*[0-9]+\.[0-9]+\.[0-9]+.*$ ]]; then
+ tag=$branch
+ else
+ echo "Tag not found in $branch. Exiting..."
+ exit 1
+ fi
+
+ echo "Tag: $tag"
+ echo "RELEASE_TAG=$tag" >> $GITHUB_ENV
+
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ inputs.git_ref || env.RELEASE_TAG }}
+ submodules: "recursive"
+
+ - name: Upload components to the component registry
+ uses: espressif/upload-components-ci-action@v1
+ with:
+ name: espasyncwebserver
+ version: ${{ env.RELEASE_TAG }}
+ namespace: esp32async
+ api_token: ${{ secrets.IDF_COMPONENT_API_TOKEN }}
diff --git a/.gitignore b/.gitignore
index 25abe6e5b..7713f05ad 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,6 @@
-.vscode
.DS_Store
/dist/
-
+.lh
+/.pio
+/.vscode
+/logs
diff --git a/.gitpod.Dockerfile b/.gitpod.Dockerfile
new file mode 100644
index 000000000..29eeb4357
--- /dev/null
+++ b/.gitpod.Dockerfile
@@ -0,0 +1,2 @@
+FROM gitpod/workspace-python-3.11
+USER gitpod
diff --git a/.gitpod.yml b/.gitpod.yml
new file mode 100644
index 000000000..2f8a4431c
--- /dev/null
+++ b/.gitpod.yml
@@ -0,0 +1,9 @@
+tasks:
+ - command: pip install --upgrade pip && pip install -U platformio && platformio run
+
+image:
+ file: .gitpod.Dockerfile
+
+vscode:
+ extensions:
+ - shardulm94.trailing-spaces
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 000000000..eb2d62e9f
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,42 @@
+exclude: |
+ (?x)(
+ ^\.github\/|
+ LICENSE$
+ )
+
+default_language_version:
+ # force all unspecified python hooks to run python3
+ python: python3
+
+repos:
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: "v5.0.0"
+ hooks:
+ # Generic checks
+ - id: check-case-conflict
+ - id: check-symlinks
+ - id: debug-statements
+ - id: destroyed-symlinks
+ - id: detect-private-key
+ - id: end-of-file-fixer
+ exclude: ^.*\.(bin|BIN)$
+ - id: mixed-line-ending
+ args: [--fix=lf]
+ - id: trailing-whitespace
+ args: [--markdown-linebreak-ext=md]
+ exclude: ^platformio\.ini$
+
+ - repo: https://github.com/codespell-project/codespell
+ rev: "v2.3.0"
+ hooks:
+ # Spell checking
+ - id: codespell
+ exclude: ^.*\.(svd|SVD)$
+
+ - repo: https://github.com/pre-commit/mirrors-clang-format
+ rev: "v18.1.3"
+ hooks:
+ # C/C++ formatting
+ - id: clang-format
+ types_or: [c, c++]
+ exclude: ^.*\/build_opt\.h$
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index e1b703527..000000000
--- a/.travis.yml
+++ /dev/null
@@ -1,46 +0,0 @@
-sudo: false
-
-language: python
-
-os:
- - linux
-
-git:
- depth: false
-
-stages:
- - build
-
-jobs:
- include:
-
- - name: "Build Arduino ESP32"
- if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
- stage: build
- script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh esp32
-
- - name: "Build Arduino ESP8266"
- if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
- stage: build
- script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh esp8266
-
- - name: "Build Platformio ESP32"
- if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
- stage: build
- script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh esp32 1 1
-
- - name: "Build Platformio ESP8266"
- if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
- stage: build
- script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh esp8266 1 1
-
-notifications:
- email:
- on_success: change
- on_failure: change
- webhooks:
- urls:
- - https://webhooks.gitter.im/e/60e65d0c78ea0a920347
- on_success: change # options: [always|never|change] default: always
- on_failure: always # options: [always|never|change] default: always
- on_start: never # options: [always|never|change] default: always
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 64292eca4..ea7be0862 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -6,12 +6,4 @@ set(COMPONENT_ADD_INCLUDEDIRS
"src"
)
-set(COMPONENT_REQUIRES
- "arduino-esp32"
- "AsyncTCP"
-)
-
register_component()
-
-target_compile_definitions(${COMPONENT_TARGET} PUBLIC -DESP32)
-target_compile_options(${COMPONENT_TARGET} PRIVATE -fno-rtti)
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 000000000..4fcdc2f52
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,129 @@
+
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socioeconomic status,
+nationality, personal appearance, race, religion, or sexual identity
+and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes,
+ and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the
+ overall community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or
+ advances of any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email
+ address, without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official e-mail address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at
+https://sidweb.nl/cms3/en/contact.
+All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the
+reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining
+the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed
+unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing
+clarity around the nature of the violation and an explanation of why the
+behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series
+of actions.
+
+**Consequence**: A warning with consequences for continued behavior. No
+interaction with the people involved, including unsolicited interaction with
+those enforcing the Code of Conduct, for a specified period of time. This
+includes avoiding interactions in community spaces as well as external channels
+like social media. Violating these terms may lead to a temporary or
+permanent ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including
+sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public
+communication with the community for a specified period of time. No public or
+private interaction with the people involved, including unsolicited interaction
+with those enforcing the Code of Conduct, is allowed during this period.
+Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community
+standards, including sustained inappropriate behavior, harassment of an
+individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within
+the community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version 2.0, available at
+https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
+
+Community Impact Guidelines were inspired by [Mozilla's code of conduct
+enforcement ladder](https://github.com/mozilla/diversity).
+
+[homepage]: https://www.contributor-covenant.org
+
+For answers to common questions about this code of conduct, see the FAQ at
+https://www.contributor-covenant.org/faq. Translations are available at
+https://www.contributor-covenant.org/translations.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..153d416dc
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
\ No newline at end of file
diff --git a/README.md b/README.md
index 0b512b86a..96eb85f3b 100644
--- a/README.md
+++ b/README.md
@@ -1,1418 +1,154 @@
# ESPAsyncWebServer
-[](https://travis-ci.org/me-no-dev/ESPAsyncWebServer)  [](https://www.codacy.com/manual/me-no-dev/ESPAsyncWebServer?utm_source=github.com&utm_medium=referral&utm_content=me-no-dev/ESPAsyncWebServer&utm_campaign=Badge_Grade)
-A fork of the [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer) library by [@me-no-dev](https://github.com/me-no-dev) for [ESPHome](https://esphome.io).
+A fork of the [ESPAsyncWebServer](https://github.com/ESP32Async/ESPAsyncWebServer) library by [@me-no-dev](https://github.com/me-no-dev) for [ESPHome](https://esphome.io).
-For help and support [](https://gitter.im/me-no-dev/ESPAsyncWebServer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+[](https://GitHub.com/ESP32Async/ESPAsyncWebServer/releases/)
+[](https://registry.platformio.org/libraries/ESP32Async/ESPAsyncWebServer)
-Async HTTP and WebSocket Server for ESP8266 Arduino
+[](https://opensource.org/license/lgpl-3-0/)
+[](code_of_conduct.md)
-For ESP8266 it requires [ESPAsyncTCP](https://github.com/me-no-dev/ESPAsyncTCP)
-To use this library you might need to have the latest git versions of [ESP8266](https://github.com/esp8266/Arduino) Arduino Core
+[](https://GitHub.com/ESP32Async/ESPAsyncWebServer/commit/)
+[](https://gitpod.io/#https://github.com/ESP32Async/ESPAsyncWebServer)
-For ESP32 it requires [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) to work
-To use this library you might need to have the latest git versions of [ESP32](https://github.com/espressif/arduino-esp32) Arduino Core
+[](https://discord.gg/X7zpGdyUcY)
-## Table of contents
-- [ESPAsyncWebServer](#espasyncwebserver)
- - [Table of contents](#table-of-contents)
- - [Installation](#installation)
- - [Using PlatformIO](#using-platformio)
- - [Why should you care](#why-should-you-care)
- - [Important things to remember](#important-things-to-remember)
- - [Principles of operation](#principles-of-operation)
- - [The Async Web server](#the-async-web-server)
- - [Request Life Cycle](#request-life-cycle)
- - [Rewrites and how do they work](#rewrites-and-how-do-they-work)
- - [Handlers and how do they work](#handlers-and-how-do-they-work)
- - [Responses and how do they work](#responses-and-how-do-they-work)
- - [Template processing](#template-processing)
- - [Libraries and projects that use AsyncWebServer](#libraries-and-projects-that-use-asyncwebserver)
- - [Request Variables](#request-variables)
- - [Common Variables](#common-variables)
- - [Headers](#headers)
- - [GET, POST and FILE parameters](#get-post-and-file-parameters)
- - [FILE Upload handling](#file-upload-handling)
- - [Body data handling](#body-data-handling)
- - [JSON body handling with ArduinoJson](#json-body-handling-with-arduinojson)
- - [Responses](#responses)
- - [Redirect to another URL](#redirect-to-another-url)
- - [Basic response with HTTP Code](#basic-response-with-http-code)
- - [Basic response with HTTP Code and extra headers](#basic-response-with-http-code-and-extra-headers)
- - [Basic response with string content](#basic-response-with-string-content)
- - [Basic response with string content and extra headers](#basic-response-with-string-content-and-extra-headers)
- - [Send large webpage from PROGMEM](#send-large-webpage-from-progmem)
- - [Send large webpage from PROGMEM and extra headers](#send-large-webpage-from-progmem-and-extra-headers)
- - [Send large webpage from PROGMEM containing templates](#send-large-webpage-from-progmem-containing-templates)
- - [Send large webpage from PROGMEM containing templates and extra headers](#send-large-webpage-from-progmem-containing-templates-and-extra-headers)
- - [Send binary content from PROGMEM](#send-binary-content-from-progmem)
- - [Respond with content coming from a Stream](#respond-with-content-coming-from-a-stream)
- - [Respond with content coming from a Stream and extra headers](#respond-with-content-coming-from-a-stream-and-extra-headers)
- - [Respond with content coming from a Stream containing templates](#respond-with-content-coming-from-a-stream-containing-templates)
- - [Respond with content coming from a Stream containing templates and extra headers](#respond-with-content-coming-from-a-stream-containing-templates-and-extra-headers)
- - [Respond with content coming from a File](#respond-with-content-coming-from-a-file)
- - [Respond with content coming from a File and extra headers](#respond-with-content-coming-from-a-file-and-extra-headers)
- - [Respond with content coming from a File containing templates](#respond-with-content-coming-from-a-file-containing-templates)
- - [Respond with content using a callback](#respond-with-content-using-a-callback)
- - [Respond with content using a callback and extra headers](#respond-with-content-using-a-callback-and-extra-headers)
- - [Respond with content using a callback containing templates](#respond-with-content-using-a-callback-containing-templates)
- - [Respond with content using a callback containing templates and extra headers](#respond-with-content-using-a-callback-containing-templates-and-extra-headers)
- - [Chunked Response](#chunked-response)
- - [Chunked Response containing templates](#chunked-response-containing-templates)
- - [Print to response](#print-to-response)
- - [ArduinoJson Basic Response](#arduinojson-basic-response)
- - [ArduinoJson Advanced Response](#arduinojson-advanced-response)
- - [Serving static files](#serving-static-files)
- - [Serving specific file by name](#serving-specific-file-by-name)
- - [Serving files in directory](#serving-files-in-directory)
- - [Serving static files with authentication](#serving-static-files-with-authentication)
- - [Specifying Cache-Control header](#specifying-cache-control-header)
- - [Specifying Date-Modified header](#specifying-date-modified-header)
- - [Specifying Template Processor callback](#specifying-template-processor-callback)
- - [Param Rewrite With Matching](#param-rewrite-with-matching)
- - [Using filters](#using-filters)
- - [Serve different site files in AP mode](#serve-different-site-files-in-ap-mode)
- - [Rewrite to different index on AP](#rewrite-to-different-index-on-ap)
- - [Serving different hosts](#serving-different-hosts)
- - [Determine interface inside callbacks](#determine-interface-inside-callbacks)
- - [Bad Responses](#bad-responses)
- - [Respond with content using a callback without content length to HTTP/1.0 clients](#respond-with-content-using-a-callback-without-content-length-to-http10-clients)
- - [Async WebSocket Plugin](#async-websocket-plugin)
- - [Async WebSocket Event](#async-websocket-event)
- - [Methods for sending data to a socket client](#methods-for-sending-data-to-a-socket-client)
- - [Direct access to web socket message buffer](#direct-access-to-web-socket-message-buffer)
- - [Limiting the number of web socket clients](#limiting-the-number-of-web-socket-clients)
- - [Async Event Source Plugin](#async-event-source-plugin)
- - [Setup Event Source on the server](#setup-event-source-on-the-server)
- - [Setup Event Source in the browser](#setup-event-source-in-the-browser)
- - [Scanning for available WiFi Networks](#scanning-for-available-wifi-networks)
- - [Remove handlers and rewrites](#remove-handlers-and-rewrites)
- - [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](#adding-default-headers)
- - [Path variable](#path-variable)
+[](https://github.com/ESP32Async/ESPAsyncWebServer/wiki)
-## Installation
+## Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266, RP2040 and RP2350
-### Using PlatformIO
+Supports: WebSocket, SSE, Authentication, Arduino Json 7, File Upload, Static File serving, URL Rewrite, URL Redirect, etc.
-[PlatformIO](http://platformio.org) is an open source ecosystem for IoT development with cross platform build system, library manager and full support for Espressif ESP8266/ESP32 development. It works on the popular host OS: Mac OS X, Windows, Linux 32/64, Linux ARM (like Raspberry Pi, BeagleBone, CubieBoard).
+- [Documentation](#documentation)
+- [How to install](#how-to-install)
+- [Dependencies](#dependencies)
+ - [ESP32 / pioarduino](#esp32--pioarduino)
+ - [ESP8266 / pioarduino](#esp8266--pioarduino)
+ - [Unofficial dependencies](#unofficial-dependencies)
-1. Install [PlatformIO IDE](http://platformio.org/platformio-ide)
-2. Create new project using "PlatformIO Home > New Project"
-3. Update dev/platform to staging version:
- - [Instruction for Espressif 8266](http://docs.platformio.org/en/latest/platforms/espressif8266.html#using-arduino-framework-with-staging-version)
- - [Instruction for Espressif 32](http://docs.platformio.org/en/latest/platforms/espressif32.html#using-arduino-framework-with-staging-version)
- 4. Add "ESP Async WebServer" to project using [Project Configuration File `platformio.ini`](http://docs.platformio.org/page/projectconf.html) and [lib_deps](http://docs.platformio.org/page/projectconf/section_env_library.html#lib-deps) option:
+## Documentation
-```ini
-[env:myboard]
-platform = espressif...
-board = ...
-framework = arduino
-
-# using the latest stable version
-lib_deps = ESP Async WebServer
-
-# or using GIT Url (the latest development version)
-lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
-```
- 5. Happy coding with PlatformIO!
-
-## 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
-- When you send the response, you are immediately ready to handle other connections
- while the server is taking care of sending the response in the background
-- Speed is OMG
-- Easy to use API, HTTP Basic and Digest MD5 Authentication (default), ChunkedResponse
-- Easily extendible to handle any type of content
-- Supports Continue 100
-- Async WebSocket plugin offering different locations without extra servers or ports
-- Async EventSource (Server-Sent Events) plugin to send events to the browser
-- URL Rewrite plugin for conditional and permanent url rewrites
-- ServeStatic plugin that supports cache, Last-Modified, default index and more
-- Simple template processing engine to handle templates
-
-## Important things to remember
-- This is fully asynchronous server and as such does not run on the loop thread.
-- You can not use yield or delay or any function that uses them inside the callbacks
-- The server is smart enough to know when to close the connection and free resources
-- You can not send more than one response to a single request
-
-## Principles of operation
-
-### The Async Web server
-- Listens for connections
-- Wraps the new clients into ```Request```
-- Keeps track of clients and cleans memory
-- Manages ```Rewrites``` and apply them on the request url
-- Manages ```Handlers``` and attaches them to Requests
-
-### Request Life Cycle
-- TCP connection is received by the server
-- The connection is wrapped inside ```Request``` object
-- When the request head is received (type, url, get params, http version and host),
- the server goes through all ```Rewrites``` (in the order they were added) to rewrite the url and inject query parameters,
- next, it goes through all attached ```Handlers```(in the order they were added) trying to find one
- that ```canHandle``` the given request. If none are found, the default(catch-all) handler is attached.
-- The rest of the request is received, calling the ```handleUpload``` or ```handleBody``` methods of the ```Handler``` if they are needed (POST+File/Body)
-- When the whole request is parsed, the result is given to the ```handleRequest``` method of the ```Handler``` and is ready to be responded to
-- In the ```handleRequest``` method, to the ```Request``` is attached a ```Response``` object (see below) that will serve the response data back to the client
-- When the ```Response``` is sent, the client is closed and freed from the memory
-
-### Rewrites and how do they work
-- The ```Rewrites``` are used to rewrite the request url and/or inject get parameters for a specific request url path.
-- All ```Rewrites``` are evaluated on the request in the order they have been added to the server.
-- The ```Rewrite``` will change the request url only if the request url (excluding get parameters) is fully match
- the rewrite url, and when the optional ```Filter``` callback return true.
-- Setting a ```Filter``` to the ```Rewrite``` enables to control when to apply the rewrite, decision can be based on
- request url, http version, request host/port/target host, get parameters or the request client's localIP or remoteIP.
-- Two filter callbacks are provided: ```ON_AP_FILTER``` to execute the rewrite when request is made to the AP interface,
- ```ON_STA_FILTER``` to execute the rewrite when request is made to the STA interface.
-- The ```Rewrite``` can specify a target url with optional get parameters, e.g. ```/to-url?with=params```
-
-### Handlers and how do they work
-- The ```Handlers``` are used for executing specific actions to particular requests
-- One ```Handler``` instance can be attached to any request and lives together with the server
-- Setting a ```Filter``` to the ```Handler``` enables to control when to apply the handler, decision can be based on
- request url, http version, request host/port/target host, get parameters or the request client's localIP or remoteIP.
-- Two filter callbacks are provided: ```ON_AP_FILTER``` to execute the rewrite when request is made to the AP interface,
- ```ON_STA_FILTER``` to execute the rewrite when request is made to the STA interface.
-- The ```canHandle``` method is used for handler specific control on whether the requests can be handled
- and for declaring any interesting headers that the ```Request``` should parse. Decision can be based on request
- method, request url, http version, request host/port/target host and get parameters
-- Once a ```Handler``` is attached to given ```Request``` (```canHandle``` returned true)
- that ```Handler``` takes care to receive any file/data upload and attach a ```Response```
- once the ```Request``` has been fully parsed
-- ```Handlers``` are evaluated in the order they are attached to the server. The ```canHandle``` is called only
- if the ```Filter``` that was set to the ```Handler``` return true.
-- The first ```Handler``` that can handle the request is selected, not further ```Filter``` and ```canHandle``` are called.
-
-### Responses and how do they work
-- The ```Response``` objects are used to send the response data back to the client
-- The ```Response``` object lives with the ```Request``` and is freed on end or disconnect
-- Different techniques are used depending on the response type to send the data in packets
- returning back almost immediately and sending the next packet when this one is received.
- Any time in between is spent to run the user loop and handle other network packets
-- Responding asynchronously is probably the most difficult thing for most to understand
-- Many different options exist for the user to make responding a background task
-
-### Template processing
-- ESPAsyncWebserver contains simple template processing engine.
-- Template processing can be added to most response types.
-- Currently it supports only replacing template placeholders with actual values. No conditional processing, cycles, etc.
-- Placeholders are delimited with ```%``` symbols. Like this: ```%TEMPLATE_PLACEHOLDER%```.
-- It works by extracting placeholder name from response text and passing it to user provided function which should return actual value to be used instead of placeholder.
-- Since it's user provided function, it is possible for library users to implement conditional processing and cycles themselves.
-- Since it's impossible to know the actual response size after template processing step in advance (and, therefore, to include it in response headers), the response becomes [chunked](#chunked-response).
-
-## Libraries and projects that use AsyncWebServer
-- [WebSocketToSerial](https://github.com/hallard/WebSocketToSerial) - Debug serial devices through the web browser
-- [Sattrack](https://github.com/Hopperpop/Sattrack) - Track the ISS with ESP8266
-- [ESP Radio](https://github.com/Edzelf/Esp-radio) - Icecast radio based on ESP8266 and VS1053
-- [VZero](https://github.com/andig/vzero) - the Wireless zero-config controller for volkszaehler.org
-- [ESPurna](https://bitbucket.org/xoseperez/espurna) - ESPurna ("spark" in Catalan) is a custom C firmware for ESP8266 based smart switches. It was originally developed with the ITead Sonoff in mind.
-- [fauxmoESP](https://bitbucket.org/xoseperez/fauxmoesp) - Belkin WeMo emulator library for ESP8266.
-- [ESP-RFID](https://github.com/omersiar/esp-rfid) - MFRC522 RFID Access Control Management project for ESP8266.
+The complete [project documentation](https://github.com/ESP32Async/ESPAsyncWebServer/wiki) is available in the Wiki section.
-## Request Variables
+## How to install
-### Common Variables
-```cpp
-request->version(); // uint8_t: 0 = HTTP/1.0, 1 = HTTP/1.1
-request->method(); // enum: HTTP_GET, HTTP_POST, HTTP_DELETE, HTTP_PUT, HTTP_PATCH, HTTP_HEAD, HTTP_OPTIONS
-request->url(); // String: URL of the request (not including host, port or GET parameters)
-request->host(); // String: The requested host (can be used for virtual hosting)
-request->contentType(); // String: ContentType of the request (not avaiable in Handler::canHandle)
-request->contentLength(); // size_t: ContentLength of the request (not avaiable in Handler::canHandle)
-request->multipart(); // bool: True if the request has content type "multipart"
-```
-
-### Headers
-```cpp
-//List all collected headers
-int headers = request->headers();
-int i;
-for(i=0;igetHeader(i);
- Serial.printf("HEADER[%s]: %s\n", h->name().c_str(), h->value().c_str());
-}
-
-//get specific header by name
-if(request->hasHeader("MyHeader")){
- AsyncWebHeader* h = request->getHeader("MyHeader");
- Serial.printf("MyHeader: %s\n", h->value().c_str());
-}
-
-//List all collected headers (Compatibility)
-int headers = request->headers();
-int i;
-for(i=0;iheaderName(i).c_str(), request->header(i).c_str());
-}
-
-//get specific header by name (Compatibility)
-if(request->hasHeader("MyHeader")){
- Serial.printf("MyHeader: %s\n", request->header("MyHeader").c_str());
-}
-```
-
-### GET, POST and FILE parameters
-```cpp
-//List all parameters
-int params = request->params();
-for(int i=0;igetParam(i);
- if(p->isFile()){ //p->isPost() is also true
- Serial.printf("FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size());
- } else if(p->isPost()){
- Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
- } else {
- Serial.printf("GET[%s]: %s\n", p->name().c_str(), p->value().c_str());
- }
-}
+The library can be downloaded from the releases page at [https://github.com/ESP32Async/ESPAsyncWebServer/releases](https://github.com/ESP32Async/ESPAsyncWebServer/releases).
-//Check if GET parameter exists
-if(request->hasParam("download"))
- AsyncWebParameter* p = request->getParam("download");
+It is also deployed in these registries:
-//Check if POST (but not File) parameter exists
-if(request->hasParam("download", true))
- AsyncWebParameter* p = request->getParam("download", true);
+- Arduino Library Registry: [https://github.com/arduino/library-registry](https://github.com/arduino/library-registry)
-//Check if FILE was uploaded
-if(request->hasParam("download", true, true))
- AsyncWebParameter* p = request->getParam("download", true, true);
+- ESP Component Registry [https://components.espressif.com/components/esp32async/espasyncwebserver](https://components.espressif.com/components/esp32async/espasyncwebserver)
-//List all parameters (Compatibility)
-int args = request->args();
-for(int i=0;iargName(i).c_str(), request->arg(i).c_str());
-}
+- PlatformIO Registry: [https://registry.platformio.org/libraries/esp32async/ESPAsyncWebServer](https://registry.platformio.org/libraries/esp32async/ESPAsyncWebServer)
-//Check if parameter exists (Compatibility)
-if(request->hasArg("download"))
- String arg = request->arg("download");
-```
-
-### FILE Upload handling
-```cpp
-void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
- if(!index){
- Serial.printf("UploadStart: %s\n", filename.c_str());
- }
- for(size_t i=0; i` to point to latest version with the same major version
+ - Use: `lib_deps=ESP32Async/ESPAsyncWebServer @ ` to always point to the same version (reproductible build)
-### Body data handling
-```cpp
-void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
- if(!index){
- Serial.printf("BodyStart: %u B\n", total);
- }
- for(size_t i=0; i();
- // ...
-});
-server.addHandler(handler);
-```
-
-## Responses
-### Redirect to another URL
-```cpp
-//to local url
-request->redirect("/login");
-
-//to external url
-request->redirect("http://esp8266.com");
-```
-
-### Basic response with HTTP Code
-```cpp
-request->send(404); //Sends 404 File Not Found
-```
-
-### Basic response with HTTP Code and extra headers
-```cpp
-AsyncWebServerResponse *response = request->beginResponse(404); //Sends 404 File Not Found
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Basic response with string content
-```cpp
-request->send(200, "text/plain", "Hello World!");
-```
-
-### Basic response with string content and extra headers
-```cpp
-AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "Hello World!");
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Send large webpage from PROGMEM
-```cpp
-const char index_html[] PROGMEM = "..."; // large char array, tested with 14k
-request->send_P(200, "text/html", index_html);
-```
-
-### Send large webpage from PROGMEM and extra headers
-```cpp
-const char index_html[] PROGMEM = "..."; // large char array, tested with 14k
-AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html);
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Send large webpage from PROGMEM containing templates
-```cpp
-String processor(const String& var)
-{
- if(var == "HELLO_FROM_TEMPLATE")
- return F("Hello world!");
- return String();
-}
-
-// ...
-
-const char index_html[] PROGMEM = "..."; // large char array, tested with 14k
-request->send_P(200, "text/html", index_html, processor);
-```
-
-### Send large webpage from PROGMEM containing templates and extra headers
-```cpp
-String processor(const String& var)
-{
- if(var == "HELLO_FROM_TEMPLATE")
- return F("Hello world!");
- return String();
-}
-
-// ...
-
-const char index_html[] PROGMEM = "..."; // large char array, tested with 14k
-AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html, processor);
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Send binary content from PROGMEM
-```cpp
-
-//File: favicon.ico.gz, Size: 726
-#define favicon_ico_gz_len 726
-const uint8_t favicon_ico_gz[] PROGMEM = {
- 0x1F, 0x8B, 0x08, 0x08, 0x0B, 0x87, 0x90, 0x57, 0x00, 0x03, 0x66, 0x61, 0x76, 0x69, 0x63, 0x6F,
- 0x6E, 0x2E, 0x69, 0x63, 0x6F, 0x00, 0xCD, 0x53, 0x5F, 0x48, 0x9A, 0x51, 0x14, 0xBF, 0x62, 0x6D,
- 0x86, 0x96, 0xA9, 0x64, 0xD3, 0xFE, 0xA8, 0x99, 0x65, 0x1A, 0xB4, 0x8A, 0xA8, 0x51, 0x54, 0x23,
- 0xA8, 0x11, 0x49, 0x51, 0x8A, 0x34, 0x62, 0x93, 0x85, 0x31, 0x58, 0x44, 0x12, 0x45, 0x2D, 0x58,
- 0xF5, 0x52, 0x41, 0x10, 0x23, 0x82, 0xA0, 0x20, 0x98, 0x2F, 0xC1, 0x26, 0xED, 0xA1, 0x20, 0x89,
- 0x04, 0xD7, 0x83, 0x58, 0x20, 0x28, 0x04, 0xAB, 0xD1, 0x9B, 0x8C, 0xE5, 0xC3, 0x60, 0x32, 0x64,
- 0x0E, 0x56, 0xBF, 0x9D, 0xEF, 0xF6, 0x30, 0x82, 0xED, 0xAD, 0x87, 0xDD, 0x8F, 0xF3, 0xDD, 0x8F,
- 0x73, 0xCF, 0xEF, 0x9C, 0xDF, 0x39, 0xBF, 0xFB, 0x31, 0x26, 0xA2, 0x27, 0x37, 0x97, 0xD1, 0x5B,
- 0xCF, 0x9E, 0x67, 0x30, 0xA6, 0x66, 0x8C, 0x99, 0xC9, 0xC8, 0x45, 0x9E, 0x6B, 0x3F, 0x5F, 0x74,
- 0xA6, 0x94, 0x5E, 0xDB, 0xFF, 0xB2, 0xE6, 0xE7, 0xE7, 0xF9, 0xDE, 0xD6, 0xD6, 0x96, 0xDB, 0xD8,
- 0xD8, 0x78, 0xBF, 0xA1, 0xA1, 0xC1, 0xDA, 0xDC, 0xDC, 0x2C, 0xEB, 0xED, 0xED, 0x15, 0x9B, 0xCD,
- 0xE6, 0x4A, 0x83, 0xC1, 0xE0, 0x2E, 0x29, 0x29, 0x99, 0xD6, 0x6A, 0xB5, 0x4F, 0x75, 0x3A, 0x9D,
- 0x61, 0x75, 0x75, 0x95, 0xB5, 0xB7, 0xB7, 0xDF, 0xC8, 0xD1, 0xD4, 0xD4, 0xF4, 0xB0, 0xBA, 0xBA,
- 0xFA, 0x83, 0xD5, 0x6A, 0xFD, 0x5A, 0x5E, 0x5E, 0x9E, 0x28, 0x2D, 0x2D, 0x0D, 0x10, 0xC6, 0x4B,
- 0x98, 0x78, 0x5E, 0x5E, 0xDE, 0x95, 0x42, 0xA1, 0x40, 0x4E, 0x4E, 0xCE, 0x65, 0x76, 0x76, 0xF6,
- 0x47, 0xB5, 0x5A, 0x6D, 0x4F, 0x26, 0x93, 0xA2, 0xD6, 0xD6, 0x56, 0x8E, 0x6D, 0x69, 0x69, 0xD1,
- 0x11, 0x36, 0x62, 0xB1, 0x58, 0x60, 0x32, 0x99, 0xA0, 0xD7, 0xEB, 0x51, 0x58, 0x58, 0x88, 0xFC,
- 0xFC, 0x7C, 0x10, 0x16, 0x02, 0x56, 0x2E, 0x97, 0x43, 0x2A, 0x95, 0x42, 0x2C, 0x16, 0x23, 0x33,
- 0x33, 0x33, 0xAE, 0x52, 0xA9, 0x1E, 0x64, 0x65, 0x65, 0x71, 0x7C, 0x7D, 0x7D, 0xBD, 0x93, 0xEA,
- 0xFE, 0x30, 0x1A, 0x8D, 0xE8, 0xEC, 0xEC, 0xC4, 0xE2, 0xE2, 0x22, 0x6A, 0x6A, 0x6A, 0x40, 0x39,
- 0x41, 0xB5, 0x38, 0x4E, 0xC8, 0x33, 0x3C, 0x3C, 0x0C, 0x87, 0xC3, 0xC1, 0x6B, 0x54, 0x54, 0x54,
- 0xBC, 0xE9, 0xEB, 0xEB, 0x93, 0x5F, 0x5C, 0x5C, 0x30, 0x8A, 0x9D, 0x2E, 0x2B, 0x2B, 0xBB, 0xA2,
- 0x3E, 0x41, 0xBD, 0x21, 0x1E, 0x8F, 0x63, 0x6A, 0x6A, 0x0A, 0x81, 0x40, 0x00, 0x94, 0x1B, 0x3D,
- 0x3D, 0x3D, 0x42, 0x3C, 0x96, 0x96, 0x96, 0x70, 0x7E, 0x7E, 0x8E, 0xE3, 0xE3, 0x63, 0xF8, 0xFD,
- 0xFE, 0xB4, 0xD7, 0xEB, 0xF5, 0x8F, 0x8F, 0x8F, 0x5B, 0x68, 0x5E, 0x6F, 0x05, 0xCE, 0xB4, 0xE3,
- 0xE8, 0xE8, 0x08, 0x27, 0x27, 0x27, 0xD8, 0xDF, 0xDF, 0xC7, 0xD9, 0xD9, 0x19, 0x6C, 0x36, 0x1B,
- 0x36, 0x36, 0x36, 0x38, 0x9F, 0x85, 0x85, 0x05, 0xAC, 0xAF, 0xAF, 0x23, 0x1A, 0x8D, 0x22, 0x91,
- 0x48, 0x20, 0x16, 0x8B, 0xFD, 0xDA, 0xDA, 0xDA, 0x7A, 0x41, 0x33, 0x7E, 0x57, 0x50, 0x50, 0x80,
- 0x89, 0x89, 0x09, 0x84, 0xC3, 0x61, 0x6C, 0x6F, 0x6F, 0x23, 0x12, 0x89, 0xE0, 0xE0, 0xE0, 0x00,
- 0x43, 0x43, 0x43, 0x58, 0x5E, 0x5E, 0xE6, 0x9C, 0x7D, 0x3E, 0x1F, 0x46, 0x47, 0x47, 0x79, 0xBE,
- 0xBD, 0xBD, 0x3D, 0xE1, 0x3C, 0x1D, 0x0C, 0x06, 0x9F, 0x10, 0xB7, 0xC7, 0x84, 0x4F, 0xF6, 0xF7,
- 0xF7, 0x63, 0x60, 0x60, 0x00, 0x83, 0x83, 0x83, 0x18, 0x19, 0x19, 0xC1, 0xDC, 0xDC, 0x1C, 0x8F,
- 0x17, 0x7C, 0xA4, 0x27, 0xE7, 0x34, 0x39, 0x39, 0x89, 0x9D, 0x9D, 0x1D, 0x6E, 0x54, 0xE3, 0x13,
- 0xE5, 0x34, 0x11, 0x37, 0x49, 0x51, 0x51, 0xD1, 0x4B, 0xA5, 0x52, 0xF9, 0x45, 0x26, 0x93, 0x5D,
- 0x0A, 0xF3, 0x92, 0x48, 0x24, 0xA0, 0x6F, 0x14, 0x17, 0x17, 0xA3, 0xB6, 0xB6, 0x16, 0x5D, 0x5D,
- 0x5D, 0x7C, 0x1E, 0xBB, 0xBB, 0xBB, 0x9C, 0xD7, 0xE1, 0xE1, 0x21, 0x42, 0xA1, 0xD0, 0x6B, 0xD2,
- 0x45, 0x4C, 0x33, 0x12, 0x34, 0xCC, 0xA0, 0x19, 0x54, 0x92, 0x56, 0x0E, 0xD2, 0xD9, 0x43, 0xF8,
- 0xCF, 0x82, 0x56, 0xC2, 0xDC, 0xEB, 0xEA, 0xEA, 0x38, 0x7E, 0x6C, 0x6C, 0x4C, 0xE0, 0xFE, 0x9D,
- 0xB8, 0xBF, 0xA7, 0xFA, 0xAF, 0x56, 0x56, 0x56, 0xEE, 0x6D, 0x6E, 0x6E, 0xDE, 0xB8, 0x47, 0x55,
- 0x55, 0x55, 0x6C, 0x66, 0x66, 0x46, 0x44, 0xDA, 0x3B, 0x34, 0x1A, 0x4D, 0x94, 0xB0, 0x3F, 0x09,
- 0x7B, 0x45, 0xBD, 0xA5, 0x5D, 0x2E, 0x57, 0x8C, 0x7A, 0x73, 0xD9, 0xED, 0xF6, 0x3B, 0x84, 0xFF,
- 0xE7, 0x7D, 0xA6, 0x3A, 0x2C, 0x95, 0x4A, 0xB1, 0x8E, 0x8E, 0x0E, 0x6D, 0x77, 0x77, 0xB7, 0xCD,
- 0xE9, 0x74, 0x3E, 0x73, 0xBB, 0xDD, 0x8F, 0x3C, 0x1E, 0x8F, 0xE6, 0xF4, 0xF4, 0x94, 0xAD, 0xAD,
- 0xAD, 0xDD, 0xDE, 0xCF, 0x73, 0x0B, 0x0B, 0xB8, 0xB6, 0xE0, 0x5D, 0xC6, 0x66, 0xC5, 0xE4, 0x10,
- 0x4C, 0xF4, 0xF7, 0xD8, 0x59, 0xF2, 0x7F, 0xA3, 0xB8, 0xB4, 0xFC, 0x0F, 0xEE, 0x37, 0x70, 0xEC,
- 0x16, 0x4A, 0x7E, 0x04, 0x00, 0x00
-};
-
-AsyncWebServerResponse *response = request->beginResponse_P(200, "image/x-icon", favicon_ico_gz, favicon_ico_gz_len);
-response->addHeader("Content-Encoding", "gzip");
-request->send(response);
-```
+## Dependencies
-### Respond with content coming from a Stream
-```cpp
-//read 12 bytes from Serial and send them as Content Type text/plain
-request->send(Serial, "text/plain", 12);
-```
-
-### Respond with content coming from a Stream and extra headers
-```cpp
-//read 12 bytes from Serial and send them as Content Type text/plain
-AsyncWebServerResponse *response = request->beginResponse(Serial, "text/plain", 12);
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Respond with content coming from a Stream containing templates
-```cpp
-String processor(const String& var)
-{
- if(var == "HELLO_FROM_TEMPLATE")
- return F("Hello world!");
- return String();
-}
-
-// ...
-
-//read 12 bytes from Serial and send them as Content Type text/plain
-request->send(Serial, "text/plain", 12, processor);
-```
-
-### Respond with content coming from a Stream containing templates and extra headers
-```cpp
-String processor(const String& var)
-{
- if(var == "HELLO_FROM_TEMPLATE")
- return F("Hello world!");
- return String();
-}
-
-// ...
-
-//read 12 bytes from Serial and send them as Content Type text/plain
-AsyncWebServerResponse *response = request->beginResponse(Serial, "text/plain", 12, processor);
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Respond with content using a callback
-```cpp
-//send 128 bytes as plain text
-request->send("text/plain", 128, [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
- //Write up to "maxLen" bytes into "buffer" and return the amount written.
- //index equals the amount of bytes that have been already sent
- //You will not be asked for more bytes once the content length has been reached.
- //Keep in mind that you can not delay or yield waiting for more data!
- //Send what you currently have and you will be asked for more again
- return mySource.read(buffer, maxLen);
-});
-```
-
-### Respond with content using a callback and extra headers
-```cpp
-//send 128 bytes as plain text
-AsyncWebServerResponse *response = request->beginResponse("text/plain", 128, [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
- //Write up to "maxLen" bytes into "buffer" and return the amount written.
- //index equals the amount of bytes that have been already sent
- //You will not be asked for more bytes once the content length has been reached.
- //Keep in mind that you can not delay or yield waiting for more data!
- //Send what you currently have and you will be asked for more again
- return mySource.read(buffer, maxLen);
-});
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Respond with content using a callback containing templates
-```cpp
-String processor(const String& var)
-{
- if(var == "HELLO_FROM_TEMPLATE")
- return F("Hello world!");
- return String();
-}
-
-// ...
-
-//send 128 bytes as plain text
-request->send("text/plain", 128, [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
- //Write up to "maxLen" bytes into "buffer" and return the amount written.
- //index equals the amount of bytes that have been already sent
- //You will not be asked for more bytes once the content length has been reached.
- //Keep in mind that you can not delay or yield waiting for more data!
- //Send what you currently have and you will be asked for more again
- return mySource.read(buffer, maxLen);
-}, processor);
-```
-
-### Respond with content using a callback containing templates and extra headers
-```cpp
-String processor(const String& var)
-{
- if(var == "HELLO_FROM_TEMPLATE")
- return F("Hello world!");
- return String();
-}
-
-// ...
-
-//send 128 bytes as plain text
-AsyncWebServerResponse *response = request->beginResponse("text/plain", 128, [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
- //Write up to "maxLen" bytes into "buffer" and return the amount written.
- //index equals the amount of bytes that have been already sent
- //You will not be asked for more bytes once the content length has been reached.
- //Keep in mind that you can not delay or yield waiting for more data!
- //Send what you currently have and you will be asked for more again
- return mySource.read(buffer, maxLen);
-}, processor);
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Chunked Response
-Used when content length is unknown. Works best if the client supports HTTP/1.1
-```cpp
-AsyncWebServerResponse *response = request->beginChunkedResponse("text/plain", [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
- //Write up to "maxLen" bytes into "buffer" and return the amount written.
- //index equals the amount of bytes that have been already sent
- //You will be asked for more data until 0 is returned
- //Keep in mind that you can not delay or yield waiting for more data!
- return mySource.read(buffer, maxLen);
-});
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Chunked Response containing templates
-Used when content length is unknown. Works best if the client supports HTTP/1.1
-```cpp
-String processor(const String& var)
-{
- if(var == "HELLO_FROM_TEMPLATE")
- return F("Hello world!");
- return String();
-}
-
-// ...
-
-AsyncWebServerResponse *response = request->beginChunkedResponse("text/plain", [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
- //Write up to "maxLen" bytes into "buffer" and return the amount written.
- //index equals the amount of bytes that have been already sent
- //You will be asked for more data until 0 is returned
- //Keep in mind that you can not delay or yield waiting for more data!
- return mySource.read(buffer, maxLen);
-}, processor);
-response->addHeader("Server","ESP Async Web Server");
-request->send(response);
-```
-
-### Print to response
-```cpp
-AsyncResponseStream *response = request->beginResponseStream("text/html");
-response->addHeader("Server","ESP Async Web Server");
-response->printf("Webpage at %s", request->url().c_str());
-
-response->print("
");
-
-response->print("");
-//send the response last
-request->send(response);
-```
-
-### ArduinoJson Basic Response
-This way of sending Json is great for when the result is below 4KB
-```cpp
-#include "AsyncJson.h"
-#include "ArduinoJson.h"
-
-
-AsyncResponseStream *response = request->beginResponseStream("application/json");
-DynamicJsonBuffer jsonBuffer;
-JsonObject &root = jsonBuffer.createObject();
-root["heap"] = ESP.getFreeHeap();
-root["ssid"] = WiFi.SSID();
-root.printTo(*response);
-request->send(response);
-```
-
-### ArduinoJson Advanced Response
-This response can handle really large Json objects (tested to 40KB)
-There isn't any noticeable speed decrease for small results with the method above
-Since ArduinoJson does not allow reading parts of the string, the whole Json has to
-be passed every time a chunks needs to be sent, which shows speed decrease proportional
-to the resulting json packets
-```cpp
-#include "AsyncJson.h"
-#include "ArduinoJson.h"
-
-
-AsyncJsonResponse * response = new AsyncJsonResponse();
-response->addHeader("Server","ESP Async Web Server");
-JsonObject& root = response->getRoot();
-root["heap"] = ESP.getFreeHeap();
-root["ssid"] = WiFi.SSID();
-response->setLength();
-request->send(response);
-```
-
-### Specifying Cache-Control header
-It is possible to specify Cache-Control header value to reduce the number of calls to the server once the client loaded
-the files. For more information on Cache-Control values see [Cache-Control](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9)
-```cpp
-// Cache responses for 10 minutes (600 seconds)
-server.serveStatic("/", SPIFFS, "/www/").setCacheControl("max-age=600");
-
-//*** Change Cache-Control after server setup ***
-
-// During setup - keep a pointer to the handler
-AsyncStaticWebHandler* handler = &server.serveStatic("/", SPIFFS, "/www/").setCacheControl("max-age=600");
-
-// At a later event - change Cache-Control
-handler->setCacheControl("max-age=30");
-```
-
-### Specifying Date-Modified header
-It is possible to specify Date-Modified header to enable the server to return Not-Modified (304) response for requests
-with "If-Modified-Since" header with the same value, instead of responding with the actual file content.
-```cpp
-// Update the date modified string every time files are updated
-server.serveStatic("/", SPIFFS, "/www/").setLastModified("Mon, 20 Jun 2016 14:00:00 GMT");
-
-//*** Chage last modified value at a later stage ***
-
-// During setup - read last modified value from config or EEPROM
-String date_modified = loadDateModified();
-AsyncStaticWebHandler* handler = &server.serveStatic("/", SPIFFS, "/www/");
-handler->setLastModified(date_modified);
-
-// At a later event when files are updated
-String date_modified = getNewDateModfied();
-saveDateModified(date_modified); // Save for next reset
-handler->setLastModified(date_modified);
-```
+### ESP32 / pioarduino
-### Specifying Template Processor callback
-It is possible to specify template processor for static files. For information on template processor see
-[Respond with content coming from a File containing templates](#respond-with-content-coming-from-a-file-containing-templates).
-```cpp
-String processor(const String& var)
-{
- if(var == "HELLO_FROM_TEMPLATE")
- return F("Hello world!");
- return String();
-}
-
-// ...
-
-server.serveStatic("/", SPIFFS, "/www/").setTemplateProcessor(processor);
-```
-
-## Param Rewrite With Matching
-It is possible to rewrite the request url with parameter matchg. Here is an example with one parameter:
-Rewrite for example "/radio/{frequence}" -> "/radio?f={frequence}"
-
-```cpp
-class OneParamRewrite : public AsyncWebRewrite
-{
- protected:
- String _urlPrefix;
- int _paramIndex;
- String _paramsBackup;
-
- public:
- OneParamRewrite(const char* from, const char* to)
- : AsyncWebRewrite(from, to) {
-
- _paramIndex = _from.indexOf('{');
-
- if( _paramIndex >=0 && _from.endsWith("}")) {
- _urlPrefix = _from.substring(0, _paramIndex);
- int index = _params.indexOf('{');
- if(index >= 0) {
- _params = _params.substring(0, index);
- }
- } else {
- _urlPrefix = _from;
- }
- _paramsBackup = _params;
- }
-
- bool match(AsyncWebServerRequest *request) override {
- if(request->url().startsWith(_urlPrefix)) {
- if(_paramIndex >= 0) {
- _params = _paramsBackup + request->url().substring(_paramIndex);
- } else {
- _params = _paramsBackup;
- }
- return true;
-
- } else {
- return false;
- }
- }
-};
-```
-
-Usage:
-
-```cpp
- server.addRewrite( new OneParamRewrite("/radio/{frequence}", "/radio?f={frequence}") );
-```
-
-## Using filters
-Filters can be set to `Rewrite` or `Handler` in order to control when to apply the rewrite and consider the handler.
-A filter is a callback function that evaluates the request and return a boolean `true` to include the item
-or `false` to exclude it.
-Two filter callback are provided for convince:
-* `ON_STA_FILTER` - return true when requests are made to the STA (station mode) interface.
-* `ON_AP_FILTER` - return true when requests are made to the AP (access point) interface.
-
-### Serving different hosts
-```cpp
-// Filter callback using request host
-bool filterOnHost1(AsyncWebServerRequest *request) { return request->host() == "host1"; }
-
-// Server setup: server files in "/host1/" to requests for "host1", and files in "/www/" otherwise.
-server.serveStatic("/", SPIFFS, "/host1/").setFilter(filterOnHost1);
-server.serveStatic("/", SPIFFS, "/www/");
-```
-
-### Determine interface inside callbacks
-```cpp
- String RedirectUrl = "http://";
- if (ON_STA_FILTER(request)) {
- RedirectUrl += WiFi.localIP().toString();
- } else {
- RedirectUrl += WiFi.softAPIP().toString();
- }
- RedirectUrl += "/index.htm";
- request->redirect(RedirectUrl);
-```
-
-## Bad Responses
-Some responses are implemented, but you should not use them, because they do not conform to HTTP.
-The following example will lead to unclean close of the connection and more time wasted
-than providing the length of the content
-
-### Respond with content using a callback without content length to HTTP/1.0 clients
-```cpp
-//This is used as fallback for chunked responses to HTTP/1.0 Clients
-request->send("text/plain", 0, [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
- //Write up to "maxLen" bytes into "buffer" and return the amount written.
- //You will be asked for more data until 0 is returned
- //Keep in mind that you can not delay or yield waiting for more data!
- return mySource.read(buffer, maxLen);
-});
-```
-
-## Async WebSocket Plugin
-The server includes a web socket plugin which lets you define different WebSocket locations to connect to
-without starting another listening service or using different port
-
-### Async WebSocket Event
-```cpp
-
-void onEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
- if(type == WS_EVT_CONNECT){
- //client connected
- os_printf("ws[%s][%u] connect\n", server->url(), client->id());
- client->printf("Hello Client %u :)", client->id());
- client->ping();
- } else if(type == WS_EVT_DISCONNECT){
- //client disconnected
- os_printf("ws[%s][%u] disconnect: %u\n", server->url(), client->id());
- } else if(type == WS_EVT_ERROR){
- //error was received from the other end
- os_printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t*)arg), (char*)data);
- } else if(type == WS_EVT_PONG){
- //pong message was received (in response to a ping request maybe)
- os_printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len)?(char*)data:"");
- } else if(type == WS_EVT_DATA){
- //data packet
- AwsFrameInfo * info = (AwsFrameInfo*)arg;
- if(info->final && info->index == 0 && info->len == len){
- //the whole message is in a single frame and we got all of it's data
- os_printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT)?"text":"binary", info->len);
- if(info->opcode == WS_TEXT){
- data[len] = 0;
- os_printf("%s\n", (char*)data);
- } else {
- for(size_t i=0; i < info->len; i++){
- os_printf("%02x ", data[i]);
- }
- os_printf("\n");
- }
- if(info->opcode == WS_TEXT)
- client->text("I got your text message");
- else
- client->binary("I got your binary message");
- } else {
- //message is comprised of multiple frames or the frame is split into multiple packets
- if(info->index == 0){
- if(info->num == 0)
- os_printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary");
- os_printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len);
- }
-
- os_printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT)?"text":"binary", info->index, info->index + len);
- if(info->message_opcode == WS_TEXT){
- data[len] = 0;
- os_printf("%s\n", (char*)data);
- } else {
- for(size_t i=0; i < len; i++){
- os_printf("%02x ", data[i]);
- }
- os_printf("\n");
- }
-
- if((info->index + len) == info->len){
- os_printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len);
- if(info->final){
- os_printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary");
- if(info->message_opcode == WS_TEXT)
- client->text("I got your text message");
- else
- client->binary("I got your binary message");
- }
- }
- }
- }
-}
-```
-
-### Methods for sending data to a socket client
-```cpp
-
-
-
-//Server methods
-AsyncWebSocket ws("/ws");
-//printf to a client
-ws.printf((uint32_t)client_id, arguments...);
-//printf to all clients
-ws.printfAll(arguments...);
-//printf_P to a client
-ws.printf_P((uint32_t)client_id, PSTR(format), arguments...);
-//printfAll_P to all clients
-ws.printfAll_P(PSTR(format), arguments...);
-//send text to a client
-ws.text((uint32_t)client_id, (char*)text);
-ws.text((uint32_t)client_id, (uint8_t*)text, (size_t)len);
-//send text from PROGMEM to a client
-ws.text((uint32_t)client_id, PSTR("text"));
-const char flash_text[] PROGMEM = "Text to send"
-ws.text((uint32_t)client_id, FPSTR(flash_text));
-//send text to all clients
-ws.textAll((char*)text);
-ws.textAll((uint8_t*)text, (size_t)len);
-//send binary to a client
-ws.binary((uint32_t)client_id, (char*)binary);
-ws.binary((uint32_t)client_id, (uint8_t*)binary, (size_t)len);
-//send binary from PROGMEM to a client
-const uint8_t flash_binary[] PROGMEM = { 0x01, 0x02, 0x03, 0x04 };
-ws.binary((uint32_t)client_id, flash_binary, 4);
-//send binary to all clients
-ws.binaryAll((char*)binary);
-ws.binaryAll((uint8_t*)binary, (size_t)len);
-//HTTP Authenticate before switch to Websocket protocol
-ws.setAuthentication("user", "pass");
-
-//client methods
-AsyncWebSocketClient * client;
-//printf
-client->printf(arguments...);
-//printf_P
-client->printf_P(PSTR(format), arguments...);
-//send text
-client->text((char*)text);
-client->text((uint8_t*)text, (size_t)len);
-//send text from PROGMEM
-client->text(PSTR("text"));
-const char flash_text[] PROGMEM = "Text to send";
-client->text(FPSTR(flash_text));
-//send binary
-client->binary((char*)binary);
-client->binary((uint8_t*)binary, (size_t)len);
-//send binary from PROGMEM
-const uint8_t flash_binary[] PROGMEM = { 0x01, 0x02, 0x03, 0x04 };
-client->binary(flash_binary, 4);
-```
-
-### Direct access to web socket message buffer
-When sending a web socket message using the above methods a buffer is created. Under certain circumstances you might want to manipulate or populate this buffer directly from your application, for example to prevent unnecessary duplications of the data. This example below shows how to create a buffer and print data to it from an ArduinoJson object then send it.
-
-```cpp
-void sendDataWs(AsyncWebSocketClient * client)
-{
- DynamicJsonBuffer jsonBuffer;
- JsonObject& root = jsonBuffer.createObject();
- root["a"] = "abc";
- root["b"] = "abcd";
- root["c"] = "abcde";
- root["d"] = "abcdef";
- root["e"] = "abcdefg";
- size_t len = root.measureLength();
- AsyncWebSocketMessageBuffer * buffer = ws.makeBuffer(len); // creates a buffer (len + 1) for you.
- if (buffer) {
- root.printTo((char *)buffer->get(), len + 1);
- if (client) {
- client->text(buffer);
- } else {
- ws.textAll(buffer);
- }
- }
-}
-```
-
-### Limiting the number of web socket clients
-Browsers sometimes do not correctly close the websocket connection, even when the close() function is called in javascript. This will eventually exhaust the web server's resources and will cause the server to crash. Periodically calling the cleanClients() function from the main loop() function limits the number of clients by closing the oldest client when the maximum number of clients has been exceeded. This can called be every cycle, however, if you wish to use less power, then calling as infrequently as once per second is sufficient.
-
-```cpp
-void loop(){
- ws.cleanupClients();
-}
-```
-
-
-## Async Event Source Plugin
-The server includes EventSource (Server-Sent Events) plugin which can be used to send short text events to the browser.
-Difference between EventSource and WebSockets is that EventSource is single direction, text-only protocol.
-
-### Setup Event Source on the server
-```cpp
-AsyncWebServer server(80);
-AsyncEventSource events("/events");
-
-void setup(){
- // setup ......
- events.onConnect([](AsyncEventSourceClient *client){
- if(client->lastId()){
- Serial.printf("Client reconnected! Last message ID that it gat is: %u\n", client->lastId());
- }
- //send event with message "hello!", id current millis
- // and set reconnect delay to 1 second
- client->send("hello!",NULL,millis(),1000);
- });
- //HTTP Basic authentication
- events.setAuthentication("user", "pass");
- server.addHandler(&events);
- // setup ......
-}
-
-void loop(){
- if(eventTriggered){ // your logic here
- //send event "myevent"
- events.send("my event content","myevent",millis());
- }
-}
-```
-
-### Setup Event Source in the browser
-```javascript
-if (!!window.EventSource) {
- var source = new EventSource('/events');
-
- source.addEventListener('open', function(e) {
- console.log("Events Connected");
- }, false);
-
- source.addEventListener('error', function(e) {
- if (e.target.readyState != EventSource.OPEN) {
- console.log("Events Disconnected");
- }
- }, false);
-
- source.addEventListener('message', function(e) {
- console.log("message", e.data);
- }, false);
-
- source.addEventListener('myevent', function(e) {
- console.log("myevent", e.data);
- }, false);
-}
-```
-
-## Scanning for available WiFi Networks
-```cpp
-//First request will return 0 results unless you start scan from somewhere else (loop/setup)
-//Do not request more often than 3-5 seconds
-server.on("/scan", HTTP_GET, [](AsyncWebServerRequest *request){
- String json = "[";
- int n = WiFi.scanComplete();
- if(n == -2){
- WiFi.scanNetworks(true);
- } else if(n){
- for (int i = 0; i < n; ++i){
- if(i) json += ",";
- json += "{";
- json += "\"rssi\":"+String(WiFi.RSSI(i));
- json += ",\"ssid\":\""+WiFi.SSID(i)+"\"";
- json += ",\"bssid\":\""+WiFi.BSSIDstr(i)+"\"";
- json += ",\"channel\":"+String(WiFi.channel(i));
- json += ",\"secure\":"+String(WiFi.encryptionType(i));
- json += ",\"hidden\":"+String(WiFi.isHidden(i)?"true":"false");
- json += "}";
- }
- WiFi.scanDelete();
- if(WiFi.scanComplete() == -2){
- WiFi.scanNetworks(true);
- }
- }
- json += "]";
- request->send(200, "application/json", json);
- json = String();
-});
-```
-
-## Remove handlers and rewrites
-
-Server goes through handlers in same order as they were added. You can't simple add handler with same path to override them.
-To remove handler:
-```arduino
-// save callback for particular URL path
-auto handler = server.on("/some/path", [](AsyncWebServerRequest *request){
- //do something useful
-});
-// when you don't need handler anymore remove it
-server.removeHandler(&handler);
-
-// same with rewrites
-server.removeRewrite(&someRewrite);
-
-server.onNotFound([](AsyncWebServerRequest *request){
- request->send(404);
-});
-
-// remove server.onNotFound handler
-server.onNotFound(NULL);
-
-// remove all rewrites, handlers and onNotFound/onFileUpload/onRequestBody callbacks
-server.reset();
-```
-
-## Setting up the server
-```cpp
-#include "ESPAsyncTCP.h"
-#include "ESPAsyncWebServer.h"
-
-AsyncWebServer server(80);
-AsyncWebSocket ws("/ws"); // access at ws://[esp ip]/ws
-AsyncEventSource events("/events"); // event source (Server-Sent events)
-
-const char* ssid = "your-ssid";
-const char* password = "your-pass";
-const char* http_username = "admin";
-const char* http_password = "admin";
-
-//flag to use from web update to reboot the ESP
-bool shouldReboot = false;
-
-void onRequest(AsyncWebServerRequest *request){
- //Handle Unknown Request
- request->send(404);
-}
-
-void onBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
- //Handle body
-}
-
-void onUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
- //Handle upload
-}
-
-void onEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
- //Handle WebSocket event
-}
-
-void setup(){
- Serial.begin(115200);
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password);
- if (WiFi.waitForConnectResult() != WL_CONNECTED) {
- Serial.printf("WiFi Failed!\n");
- return;
- }
-
- // attach AsyncWebSocket
- ws.onEvent(onEvent);
- server.addHandler(&ws);
-
- // attach AsyncEventSource
- server.addHandler(&events);
-
- // respond to GET requests on URL /heap
- server.on("/heap", HTTP_GET, [](AsyncWebServerRequest *request){
- request->send(200, "text/plain", String(ESP.getFreeHeap()));
- });
-
- // upload a file to /upload
- server.on("/upload", HTTP_POST, [](AsyncWebServerRequest *request){
- request->send(200);
- }, onUpload);
-
- // send a file when /index is requested
- server.on("/index", HTTP_ANY, [](AsyncWebServerRequest *request){
- request->send(SPIFFS, "/index.htm");
- });
-
- // HTTP basic authentication
- server.on("/login", HTTP_GET, [](AsyncWebServerRequest *request){
- if(!request->authenticate(http_username, http_password))
- return request->requestAuthentication();
- request->send(200, "text/plain", "Login Success!");
- });
-
- // Simple Firmware Update Form
- server.on("/update", HTTP_GET, [](AsyncWebServerRequest *request){
- request->send(200, "text/html", "");
- });
- server.on("/update", HTTP_POST, [](AsyncWebServerRequest *request){
- shouldReboot = !Update.hasError();
- AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", shouldReboot?"OK":"FAIL");
- response->addHeader("Connection", "close");
- request->send(response);
- },[](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
- if(!index){
- Serial.printf("Update Start: %s\n", filename.c_str());
- Update.runAsync(true);
- if(!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)){
- Update.printError(Serial);
- }
- }
- if(!Update.hasError()){
- if(Update.write(data, len) != len){
- Update.printError(Serial);
- }
- }
- if(final){
- if(Update.end(true)){
- Serial.printf("Update Success: %uB\n", index+len);
- } else {
- Update.printError(Serial);
- }
- }
- });
-
- // Catch-All Handlers
- // Any request that can not find a Handler that canHandle it
- // ends in the callbacks below.
- server.onNotFound(onRequest);
- server.onFileUpload(onUpload);
- server.onRequestBody(onBody);
-
- server.begin();
-}
-
-void loop(){
- if(shouldReboot){
- Serial.println("Rebooting...");
- delay(100);
- ESP.restart();
- }
- static char temp[128];
- sprintf(temp, "Seconds since boot: %u", millis()/1000);
- events.send(temp, "time"); //send event "time"
-}
-```
-
-### Setup global and class functions as request handlers
-
-```cpp
-#include
-#include
-#include
-#include
-
-void handleRequest(AsyncWebServerRequest *request){}
-
-class WebClass {
-public :
- AsyncWebServer classWebServer = AsyncWebServer(81);
-
- WebClass(){};
-
- void classRequest (AsyncWebServerRequest *request){}
-
- void begin(){
- // attach global request handler
- classWebServer.on("/example", HTTP_ANY, handleRequest);
-
- // attach class request handler
- classWebServer.on("/example", HTTP_ANY, std::bind(&WebClass::classRequest, this, std::placeholders::_1));
- }
-};
-
-AsyncWebServer globalWebServer(80);
-WebClass webClassInstance;
-
-void setup() {
- // attach global request handler
- globalWebServer.on("/example", HTTP_ANY, handleRequest);
-
- // attach class request handler
- globalWebServer.on("/example", HTTP_ANY, std::bind(&WebClass::classRequest, webClassInstance, std::placeholders::_1));
-}
-
-void loop() {
-
-}
+```ini
+[env:stable]
+platform = https://github.com/pioarduino/platform-espressif32/releases/download/stable/platform-espressif32.zip
+lib_compat_mode = strict
+lib_ldf_mode = chain
+lib_deps =
+ ESP32Async/AsyncTCP
+ ESP32Async/ESPAsyncWebServer
```
-### Methods for controlling websocket connections
-
-```cpp
- // Disable client connections if it was activated
- if ( ws.enabled() )
- ws.enable(false);
+### ESP8266 / pioarduino
- // enable client connections if it was disabled
- if ( !ws.enabled() )
- ws.enable(true);
+```ini
+[env:stable]
+platform = espressif8266
+lib_compat_mode = strict
+lib_ldf_mode = chain
+lib_deps =
+ ESP32Async/ESPAsyncTCP
+ ESP32Async/ESPAsyncWebServer
```
-Example of OTA code
-
-```cpp
- // OTA callbacks
- ArduinoOTA.onStart([]() {
- // Disable client connections
- ws.enable(false);
+### LibreTiny (BK7231N/T, RTL8710B, etc.)
- // Advertise connected clients what's going on
- ws.textAll("OTA Update Started");
-
- // Close them
- ws.closeAll();
-
- });
+Version 1.9.1 or newer is required.
+```ini
+[env:stable]
+platform = libretiny @ ^1.9.1
+lib_ldf_mode = chain
+lib_deps =
+ ESP32Async/AsyncTCP
+ ESP32Async/ESPAsyncWebServer
```
-### Adding Default Headers
+### Unofficial dependencies
-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.
+**AsyncTCPSock**
-Example:
+AsyncTCPSock can be used instead of AsyncTCP by excluding AsyncTCP from the library dependencies and adding AsyncTCPSock instead:
-```cpp
-DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
-webServer.begin();
+```ini
+lib_compat_mode = strict
+lib_ldf_mode = chain
+lib_deps =
+ https://github.com/ESP32Async/AsyncTCPSock/archive/refs/tags/v1.0.3-dev.zip
+ ESP32Async/ESPAsyncWebServer
+lib_ignore =
+ AsyncTCP
+ ESP32Async/AsyncTCP
```
-*NOTE*: You will still need to respond to the OPTIONS method for CORS pre-flight in most cases. (unless you are only using GET)
+**RPAsyncTCP**
-This is one option:
+RPAsyncTCP replaces AsyncTCP to provide support for RP2040(+WiFi) and RP2350(+WiFi) boards. For example - Raspberry Pi Pico W and Raspberry Pi Pico 2W.
-```cpp
-webServer.onNotFound([](AsyncWebServerRequest *request) {
- if (request->method() == HTTP_OPTIONS) {
- request->send(200);
- } else {
- request->send(404);
- }
-});
+```ini
+lib_compat_mode = strict
+lib_ldf_mode = chain
+platform = https://github.com/maxgerhardt/platform-raspberrypi.git
+board = rpipicow
+board_build.core = earlephilhower
+lib_deps =
+ ayushsharma82/RPAsyncTCP@^1.3.2
+ ESP32Async/ESPAsyncWebServer
+lib_ignore =
+ lwIP_ESPHost
+build_flags = ${env.build_flags}
+ -Wno-missing-field-initializers
```
-### Path variable
+## Important recommendations for build options
-With path variable you can create a custom regex rule for a specific parameter in a route.
-For example we want a `sensorId` parameter in a route rule to match only a integer.
+Most of the crashes are caused by improper use or configuration of the AsyncTCP library used for the project.
+Here are some recommendations to avoid them and build-time flags you can change.
-```cpp
- server.on("^\\/sensor\\/([0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) {
- String sensorId = request->pathArg(0);
- });
-```
-*NOTE*: All regex patterns starts with `^` and ends with `$`
+`CONFIG_ASYNC_TCP_MAX_ACK_TIME` - defines a timeout for TCP connection to be considered alive when waiting for data.
+In some bad network conditions you might consider increasing it.
-To enable the `Path variable` support, you have to define the buildflag `-DASYNCWEBSERVER_REGEX`.
+`CONFIG_ASYNC_TCP_QUEUE_SIZE` - defines the length of the queue for events related to connections handling.
+Both the server and AsyncTCP library were optimized to control the queue automatically. Do NOT try blindly increasing the queue size, it does not help you in a way you might think it is. If you receive debug messages about queue throttling, try to optimize your server callbacks code to execute as fast as possible.
+Read #165 thread, it might give you some hints.
+`CONFIG_ASYNC_TCP_RUNNING_CORE` - CPU core thread affinity that runs the queue events handling and executes server callbacks. Default is ANY core, so it means that for dualcore SoCs both cores could handle server activities. If your server's code is too heavy and unoptimized or you see that sometimes
+server might affect other network activities, you might consider to bind it to the same core that runs Arduino code (1) to minimize affect on radio part. Otherwise you can leave the default to let RTOS decide where to run the thread based on priority
-For Arduino IDE create/update `platform.local.txt`:
+`CONFIG_ASYNC_TCP_STACK_SIZE` - stack size for the thread that runs sever events and callbacks. Default is 16k that is a way too much waste for well-defined short async code or simple static file handling. You might want to cosider reducing it to 4-8k to same RAM usage. If you do not know what this is or not sure about your callback code demands - leave it as default, should be enough even for very hungry callbacks in most cases.
-`Windows`: C:\Users\(username)\AppData\Local\Arduino15\packages\\`{espxxxx}`\hardware\\`espxxxx`\\`{version}`\platform.local.txt
+> [!NOTE]
+> This relates to ESP32 only, ESP8266 uses different ESPAsyncTCP lib that does not has this build options
-`Linux`: ~/.arduino15/packages/`{espxxxx}`/hardware/`{espxxxx}`/`{version}`/platform.local.txt
+I personally use the following configuration in my projects:
-Add/Update the following line:
-```
- compiler.cpp.extra_flags=-DDASYNCWEBSERVER_REGEX
+```c++
+ -D CONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 // (keep default)
+ -D CONFIG_ASYNC_TCP_PRIORITY=10 // (keep default)
+ -D CONFIG_ASYNC_TCP_QUEUE_SIZE=64 // (keep default)
+ -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 // force async_tcp task to be on same core as Arduino app (default is any core)
+ -D CONFIG_ASYNC_TCP_STACK_SIZE=4096 // reduce the stack size (default is 16K)
```
-For platformio modify `platformio.ini`:
-```ini
-[env:myboard]
-build_flags =
- -DASYNCWEBSERVER_REGEX
-```
-*NOTE*: By enabling `ASYNCWEBSERVER_REGEX`, `` will be included. This will add an 100k to your binary.
+If you need to serve chunk requests with a really low buffer (which should be avoided), you can set `-D ASYNCWEBSERVER_USE_CHUNK_INFLIGHT=0` to disable the in-flight control.
diff --git a/_config.yml b/_config.yml
deleted file mode 100644
index c4192631f..000000000
--- a/_config.yml
+++ /dev/null
@@ -1 +0,0 @@
-theme: jekyll-theme-cayman
\ No newline at end of file
diff --git a/component.mk b/component.mk
deleted file mode 100644
index bb5bb1614..000000000
--- a/component.mk
+++ /dev/null
@@ -1,3 +0,0 @@
-COMPONENT_ADD_INCLUDEDIRS := src
-COMPONENT_SRCDIRS := src
-CXXFLAGS += -fno-rtti
diff --git a/data/README.md b/data/README.md
new file mode 100644
index 000000000..96a2ee4f8
--- /dev/null
+++ b/data/README.md
@@ -0,0 +1,48 @@
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+dapibus elit, id varius sem dui id lacus.
diff --git a/docs/logo.png b/docs/logo.png
new file mode 100644
index 000000000..1995c88b9
Binary files /dev/null and b/docs/logo.png differ
diff --git a/docs/logo.webp b/docs/logo.webp
new file mode 100644
index 000000000..c70b84209
Binary files /dev/null and b/docs/logo.webp differ
diff --git a/docs/perf-c10-asynctcpsock.png b/docs/perf-c10-asynctcpsock.png
new file mode 100644
index 000000000..b1d4d7aa6
Binary files /dev/null and b/docs/perf-c10-asynctcpsock.png differ
diff --git a/docs/perf-c10.png b/docs/perf-c10.png
new file mode 100644
index 000000000..e63e71a88
Binary files /dev/null and b/docs/perf-c10.png differ
diff --git a/examples/AsyncResponseStream/AsyncResponseStream.ino b/examples/AsyncResponseStream/AsyncResponseStream.ino
new file mode 100644
index 000000000..451bb1a11
--- /dev/null
+++ b/examples/AsyncResponseStream/AsyncResponseStream.ino
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+static AsyncWebServer server(80);
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // Shows how to use AsyncResponseStream.
+ // The internal buffer will be allocated and data appended to it,
+ // until the response is sent, then this buffer is read and committed on the network.
+ //
+ // curl -v http://192.168.4.1/
+ //
+ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
+ AsyncResponseStream *response = request->beginResponseStream("plain/text", 40 * 1024);
+ for (int i = 0; i < 32 * 1024; i++) {
+ response->write('a');
+ }
+ request->send(response);
+ });
+
+ server.begin();
+}
+
+void loop() {
+ delay(100);
+}
diff --git a/examples/AsyncTunnel/AsyncTunnel.ino b/examples/AsyncTunnel/AsyncTunnel.ino
new file mode 100644
index 000000000..b63c056a9
--- /dev/null
+++ b/examples/AsyncTunnel/AsyncTunnel.ino
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Shows how to trigger an async client request from a browser request and send the client response back to the browser through websocket
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+#define WIFI_SSID "IoT"
+#define WIFI_PASSWORD ""
+
+static AsyncWebServer server(80);
+static AsyncWebSocketMessageHandler wsHandler;
+static AsyncWebSocket ws("/ws", wsHandler.eventHandler());
+
+static const char *htmlContent PROGMEM = R"(
+
+
+
+ WebSocket Tunnel Example
+
+
+
", WiFi.softAPIP().toString().c_str());
+#endif
response->print("");
request->send(response);
}
};
+void setup() {
+ Serial.begin(115200);
+ Serial.println();
+ Serial.println("Configuring access point...");
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ if (!WiFi.softAP("esp-captive")) {
+ Serial.println("Soft AP creation failed.");
+ while (1);
+ }
-void setup(){
- //your other setup stuff...
- WiFi.softAP("esp-captive");
dnsServer.start(53, "*", WiFi.softAPIP());
- server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER);//only when requested from AP
- //more handlers...
+#endif
+
+ server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER); // only when requested from AP
+ // more handlers...
server.begin();
}
-void loop(){
+void loop() {
dnsServer.processNextRequest();
}
diff --git a/examples/CatchAllHandler/CatchAllHandler.ino b/examples/CatchAllHandler/CatchAllHandler.ino
new file mode 100644
index 000000000..fb0141031
--- /dev/null
+++ b/examples/CatchAllHandler/CatchAllHandler.ino
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Shows how to catch all requests and send a 404 Not Found response
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+static AsyncWebServer server(80);
+
+static const char *htmlContent PROGMEM = R"(
+
+
+
+ Sample HTML
+
+
+
Hello, World!
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
+
+)";
+
+static const size_t htmlContentLength = strlen_P(htmlContent);
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // curl -v http://192.168.4.1/
+ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
+ // need to cast to uint8_t*
+ // if you do not, the const char* will be copied in a temporary String buffer
+ request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength);
+ });
+
+ // catch any request, and send a 404 Not Found response
+ // except for /game_log which is handled by onRequestBody
+ //
+ // curl -v http://192.168.4.1/foo
+ //
+ server.onNotFound([](AsyncWebServerRequest *request) {
+ if (request->url() == "/game_log") {
+ return; // response object already created by onRequestBody
+ }
+
+ request->send(404, "text/plain", "Not found");
+ });
+
+ // See: https://github.com/ESP32Async/ESPAsyncWebServer/issues/6
+ // catch any POST request and send a 200 OK response
+ //
+ // curl -v -X POST http://192.168.4.1/game_log -H "Content-Type: application/json" -d '{"game": "test"}'
+ //
+ server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
+ if (request->url() == "/game_log") {
+ request->send(200, "application/json", "{\"status\":\"OK\"}");
+ }
+ // note that there is no else here: the goal is only to prepare a response based on some body content
+ // onNotFound will always be called after this, and will not override the response object if `/game_log` is requested
+ });
+
+ server.begin();
+}
+
+// not needed
+void loop() {
+ delay(100);
+}
diff --git a/examples/ChunkResponse/ChunkResponse.ino b/examples/ChunkResponse/ChunkResponse.ino
new file mode 100644
index 000000000..52c31c0cd
--- /dev/null
+++ b/examples/ChunkResponse/ChunkResponse.ino
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Chunk response with caching example
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+static AsyncWebServer server(80);
+
+static const char *htmlContent PROGMEM = R"(
+
+
+
+ Sample HTML
+
+
+
Hello, World!
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
+
+)";
+
+static const size_t htmlContentLength = strlen_P(htmlContent);
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // first time: serves the file and cache headers
+ // curl -N -v http://192.168.4.1/ --output -
+ //
+ // secodn time: serves 304
+ // curl -N -v -H "if-none-match: 4272" http://192.168.4.1/ --output -
+ //
+ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
+ String etag = String(htmlContentLength);
+
+ if (request->header(asyncsrv::T_INM) == etag) {
+ request->send(304);
+ return;
+ }
+
+ AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
+ Serial.printf("%u / %u\n", index, htmlContentLength);
+
+ // finished ?
+ if (htmlContentLength <= index) {
+ Serial.println("finished");
+ return 0;
+ }
+
+ // serve a maximum of 256 or maxLen bytes of the remaining content
+ // this small number is specifically chosen to demonstrate the chunking
+ // DO NOT USE SUCH SMALL NUMBER IN PRODUCTION
+ // Reducing the chunk size will increase the response time, thus reducing the server's capacity in processing concurrent requests
+ const int chunkSize = min((size_t)256, min(maxLen, htmlContentLength - index));
+ Serial.printf("sending: %u\n", chunkSize);
+
+ memcpy(buffer, htmlContent + index, chunkSize);
+
+ return chunkSize;
+ });
+
+ response->addHeader(asyncsrv::T_Cache_Control, "public,max-age=60");
+ response->addHeader(asyncsrv::T_ETag, etag);
+
+ request->send(response);
+ });
+
+ server.begin();
+}
+
+void loop() {
+ delay(100);
+}
diff --git a/examples/ChunkRetryResponse/ChunkRetryResponse.ino b/examples/ChunkRetryResponse/ChunkRetryResponse.ino
new file mode 100644
index 000000000..4e67edb30
--- /dev/null
+++ b/examples/ChunkRetryResponse/ChunkRetryResponse.ino
@@ -0,0 +1,229 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Shows how to wait in a chunk response for incoming data
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+#if __has_include("ArduinoJson.h")
+#include
+#include
+#include
+#endif
+
+static const char *htmlContent PROGMEM = R"(
+
+
+
+ Sample HTML
+
+
+
Hello, World!
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
+
+)";
+
+static const size_t htmlContentLength = strlen_P(htmlContent);
+
+static AsyncWebServer server(80);
+static AsyncLoggingMiddleware requestLogger;
+
+static String triggerUART;
+static int key = -1;
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // adds some internal request logging for debugging
+ requestLogger.setEnabled(true);
+ requestLogger.setOutput(Serial);
+
+ server.addMiddleware(&requestLogger);
+
+#if __has_include("ArduinoJson.h")
+
+ //
+ // HOW TO RUN THIS EXAMPLE:
+ //
+ // 1. Trigger a request that will be blocked for a long time:
+ // > time curl -v -X POST http://192.168.4.1/api -H "Content-Type: application/json" -d '{"input": "Please type a key to continue in Serial console..."}' --output -
+ //
+ // 2. While waiting, in another terminal, run some concurrent requests:
+ // > time curl -v http://192.168.4.1/
+ //
+ // 3. Type a key in the Serial console to continue the processing within 30 seconds.
+ // This should unblock the first request.
+ //
+ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
+ // need to cast to uint8_t*
+ // if you do not, the const char* will be copied in a temporary String buffer
+ request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength);
+ });
+
+ server.on(
+ "/api", HTTP_POST,
+ [](AsyncWebServerRequest *request) {
+ // request parsing has finished
+ String *data = (String *)request->_tempObject;
+
+ if (!data) {
+ request->send(400);
+ return;
+ }
+
+ // no data ?
+ if (!data->length()) {
+ delete data;
+ request->_tempObject = nullptr;
+ request->send(400);
+ return;
+ }
+
+ JsonDocument doc;
+
+ // deserialize and check for errors
+ if (deserializeJson(doc, *data)) {
+ delete data;
+ request->_tempObject = nullptr;
+ request->send(400);
+ return;
+ }
+
+ delete data;
+ request->_tempObject = nullptr;
+
+ // start UART com: UART will send the data to the Serial console and wait for the key press
+ triggerUART = doc["input"].as();
+ key = -1;
+
+ AsyncWebServerResponse *response = request->beginChunkedResponse("text/plain", [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
+ // still waiting for UARY ?
+ if (triggerUART.length() && key == -1) {
+ return RESPONSE_TRY_AGAIN;
+ }
+
+ // finished ?
+ if (!triggerUART.length() && key == -1) {
+ return 0; // 0 means we are done
+ }
+
+ // log_d("UART answered!");
+
+ String answer = "You typed: ";
+ answer.concat((char)key);
+
+ // note: I did not check for maxLen, but you should (see ChunkResponse.ino)
+ memcpy(buffer, answer.c_str(), answer.length());
+
+ // finish!
+ triggerUART = emptyString;
+ key = -1;
+
+ return answer.length();
+ });
+
+ request->send(response);
+ },
+ NULL, // upload handler is not used so it should be NULL
+ [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
+ // log_d("Body: index: %u, len: %u, total: %u", index, len, total);
+
+ if (!index) {
+ // log_d("Start body parsing");
+ request->_tempObject = new String();
+ // cast request->_tempObject pointer to String and reserve total size
+ ((String *)request->_tempObject)->reserve(total);
+ // set timeout 30s
+ request->client()->setRxTimeout(30);
+ }
+
+ // log_d("Append body data");
+ ((String *)request->_tempObject)->concat((const char *)data, len);
+ }
+ );
+
+#endif
+
+ server.begin();
+}
+
+void loop() {
+ if (triggerUART.length() && key == -1) {
+ Serial.println(triggerUART);
+ // log_d("Waiting for UART input...");
+ while (!Serial.available()) {
+ delay(100);
+ }
+ key = Serial.read();
+ Serial.flush();
+ // log_d("UART input: %c", key);
+ triggerUART = emptyString;
+ }
+}
diff --git a/examples/EndBegin/EndBegin.ino b/examples/EndBegin/EndBegin.ino
new file mode 100644
index 000000000..8e91fcf41
--- /dev/null
+++ b/examples/EndBegin/EndBegin.ino
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// https://github.com/ESP32Async/ESPAsyncWebServer/discussions/23
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+static AsyncWebServer server(80);
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
+ request->send(200, "text/plain", "Hello, world");
+ });
+
+ server.begin();
+ Serial.println("begin() - run: curl -v http://192.168.4.1/ => should succeed");
+ delay(10000);
+
+ Serial.println("end()");
+ server.end();
+ server.begin();
+ Serial.println("begin() - run: curl -v http://192.168.4.1/ => should succeed");
+}
+
+// not needed
+void loop() {
+ delay(100);
+}
diff --git a/examples/Filters/Filters.ino b/examples/Filters/Filters.ino
new file mode 100644
index 000000000..bcdb5b3c5
--- /dev/null
+++ b/examples/Filters/Filters.ino
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Shows how to use setFilter to route requests to different handlers based on WiFi mode
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+#include "ESPAsyncWebServer.h"
+
+static DNSServer dnsServer;
+static AsyncWebServer server(80);
+
+class CaptiveRequestHandler : public AsyncWebHandler {
+public:
+ bool canHandle(__unused AsyncWebServerRequest *request) const override {
+ return true;
+ }
+
+ void handleRequest(AsyncWebServerRequest *request) override {
+ AsyncResponseStream *response = request->beginResponseStream("text/html");
+ response->print("Captive Portal");
+ response->print("
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
+ rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
+ arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
+ accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
+ Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
+ dapibus elit, id varius sem dui id lacus.
+
+
+)";
+
+static const size_t htmlContentLength = strlen_P(htmlContent);
+static constexpr char characters[] = "0123456789ABCDEF";
+static size_t charactersIndex = 0;
+
+static AsyncWebServer server(80);
+static AsyncEventSource events("/events");
+
+static volatile size_t requests = 0;
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // Pauses in the request parsing phase
+ //
+ // autocannon -c 32 -w 32 -a 96 -t 30 --renderStatusCodes -m POST -H "Content-Type: application/json" -b '{"foo": "bar"}' http://192.168.4.1/delay
+ //
+ // curl -v -X POST -H "Content-Type: application/json" -d '{"game": "test"}' http://192.168.4.1/delay
+ //
+ server.onNotFound([](AsyncWebServerRequest *request) {
+ requests = requests + 1;
+ if (request->url() == "/delay") {
+ request->send(200, "application/json", "{\"status\":\"OK\"}");
+ } else {
+ request->send(404, "text/plain", "Not found");
+ }
+ });
+ server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
+ if (request->url() == "/delay") {
+ delay(3000);
+ }
+ });
+
+ // HTTP endpoint
+ //
+ // > brew install autocannon
+ // > autocannon -c 10 -w 10 -d 20 http://192.168.4.1
+ // > autocannon -c 16 -w 16 -d 20 http://192.168.4.1
+ //
+ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
+ // need to cast to uint8_t*
+ // if you do not, the const char* will be copied in a temporary String buffer
+ requests = requests + 1;
+ request->send(200, "text/html", (uint8_t *)htmlContent, htmlContentLength);
+ });
+
+ // IMPORTANT - DO NOT WRITE SUCH CODE IN PRODUCTON !
+ //
+ // This example simulates the slowdown that can happen when:
+ // - downloading a huge file from sdcard
+ // - doing some file listing on SDCard because it is horribly slow to get a file listing with file stats on SDCard.
+ // So in both cases, ESP would deadlock or TWDT would trigger.
+ //
+ // This example simulats that by slowing down the chunk callback:
+ // - d=2000 is the delay in ms in the callback
+ // - l=10000 is the length of the response
+ //
+ // time curl -N -v -G -d 'd=2000' -d 'l=10000' http://192.168.4.1/slow.html --output -
+ //
+ server.on("/slow.html", HTTP_GET, [](AsyncWebServerRequest *request) {
+ requests = requests + 1;
+ uint32_t d = request->getParam("d")->value().toInt();
+ uint32_t l = request->getParam("l")->value().toInt();
+ Serial.printf("d = %" PRIu32 ", l = %" PRIu32 "\n", d, l);
+ AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [d, l](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
+ Serial.printf("%u\n", index);
+ // finished ?
+ if (index >= l) {
+ return 0;
+ }
+
+ // slow down the task to simulate some heavy processing, like SD card reading
+ delay(d);
+
+ memset(buffer, characters[charactersIndex], 256);
+ charactersIndex = (charactersIndex + 1) % sizeof(characters);
+ return 256;
+ });
+
+ request->send(response);
+ });
+
+ // SSS endpoint
+ //
+ // launch 16 concurrent workers for 30 seconds
+ // > for i in {1..10}; do ( count=$(gtimeout 30 curl -s -N -H "Accept: text/event-stream" http://192.168.4.1/events 2>&1 | grep -c "^data:"); echo "Total: $count events, $(echo "$count / 4" | bc -l) events / second" ) & done;
+ // > for i in {1..16}; do ( count=$(gtimeout 30 curl -s -N -H "Accept: text/event-stream" http://192.168.4.1/events 2>&1 | grep -c "^data:"); echo "Total: $count events, $(echo "$count / 4" | bc -l) events / second" ) & done;
+ //
+ // With AsyncTCP, with 16 workers: a lot of "Event message queue overflow: discard message", no crash
+ //
+ // Total: 1711 events, 427.75 events / second
+ // Total: 1711 events, 427.75 events / second
+ // Total: 1626 events, 406.50 events / second
+ // Total: 1562 events, 390.50 events / second
+ // Total: 1706 events, 426.50 events / second
+ // Total: 1659 events, 414.75 events / second
+ // Total: 1624 events, 406.00 events / second
+ // Total: 1706 events, 426.50 events / second
+ // Total: 1487 events, 371.75 events / second
+ // Total: 1573 events, 393.25 events / second
+ // Total: 1569 events, 392.25 events / second
+ // Total: 1559 events, 389.75 events / second
+ // Total: 1560 events, 390.00 events / second
+ // Total: 1562 events, 390.50 events / second
+ // Total: 1626 events, 406.50 events / second
+ //
+ // With AsyncTCP, with 10 workers:
+ //
+ // Total: 2038 events, 509.50 events / second
+ // Total: 2120 events, 530.00 events / second
+ // Total: 2119 events, 529.75 events / second
+ // Total: 2038 events, 509.50 events / second
+ // Total: 2037 events, 509.25 events / second
+ // Total: 2119 events, 529.75 events / second
+ // Total: 2119 events, 529.75 events / second
+ // Total: 2120 events, 530.00 events / second
+ // Total: 2038 events, 509.50 events / second
+ // Total: 2038 events, 509.50 events / second
+ //
+ // With AsyncTCPSock, with 16 workers: ESP32 CRASH !!!
+ //
+ // With AsyncTCPSock, with 10 workers:
+ //
+ // Total: 1242 events, 310.50 events / second
+ // Total: 1242 events, 310.50 events / second
+ // Total: 1242 events, 310.50 events / second
+ // Total: 1242 events, 310.50 events / second
+ // Total: 1181 events, 295.25 events / second
+ // Total: 1182 events, 295.50 events / second
+ // Total: 1240 events, 310.00 events / second
+ // Total: 1181 events, 295.25 events / second
+ // Total: 1181 events, 295.25 events / second
+ // Total: 1183 events, 295.75 events / second
+ //
+ server.addHandler(&events);
+
+ server.begin();
+}
+
+static uint32_t lastSSE = 0;
+static uint32_t deltaSSE = 10;
+
+static uint32_t lastHeap = 0;
+
+void loop() {
+ uint32_t now = millis();
+ if (now - lastSSE >= deltaSSE) {
+ events.send(String("ping-") + now, "heartbeat", now);
+ lastSSE = millis();
+ }
+
+#ifdef ESP32
+ if (now - lastHeap >= 2000) {
+ Serial.printf("Uptime: %3lu s, requests: %3u, Free heap: %" PRIu32 "\n", millis() / 1000, requests, ESP.getFreeHeap());
+ lastHeap = now;
+ }
+#endif
+}
diff --git a/examples/RateLimit/RateLimit.ino b/examples/RateLimit/RateLimit.ino
new file mode 100644
index 000000000..5ae93e784
--- /dev/null
+++ b/examples/RateLimit/RateLimit.ino
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Show how to rate limit the server or some endpoints
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+static AsyncWebServer server(80);
+static AsyncRateLimitMiddleware rateLimit;
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // maximum 5 requests per 10 seconds
+ rateLimit.setMaxRequests(5);
+ rateLimit.setWindowSize(10);
+
+ // run quickly several times:
+ //
+ // curl -v http://192.168.4.1/
+ //
+ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
+ request->send(200, "text/plain", "Hello, world!");
+ });
+
+ // run quickly several times:
+ //
+ // curl -v http://192.168.4.1/rate-limited
+ //
+ server
+ .on(
+ "/rate-limited", HTTP_GET,
+ [](AsyncWebServerRequest *request) {
+ request->send(200, "text/plain", "Hello, world!");
+ }
+ )
+ .addMiddleware(&rateLimit); // only rate limit this endpoint, but could be applied globally to the server
+
+ server.begin();
+}
+
+// not needed
+void loop() {
+ delay(100);
+}
diff --git a/examples/Redirect/Redirect.ino b/examples/Redirect/Redirect.ino
new file mode 100644
index 000000000..8f105573c
--- /dev/null
+++ b/examples/Redirect/Redirect.ino
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Shows how to redirect
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+static AsyncWebServer server(80);
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // curl -v http://192.168.4.1/
+ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
+ request->redirect("/index.txt");
+ });
+
+ // curl -v http://192.168.4.1/index.txt
+ server.on("/index.txt", HTTP_GET, [](AsyncWebServerRequest *request) {
+ request->send(200, "text/plain", "Hello, world!");
+ });
+
+ server.begin();
+}
+
+// not needed
+void loop() {
+ delay(100);
+}
diff --git a/examples/RequestContinuation/RequestContinuation.ino b/examples/RequestContinuation/RequestContinuation.ino
new file mode 100644
index 000000000..f59322e5d
--- /dev/null
+++ b/examples/RequestContinuation/RequestContinuation.ino
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Shows how to use request continuation to pause a request for a long processing task, and be able to resume it later.
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+#include
+#include
+
+static AsyncWebServer server(80);
+
+// request handler that is saved from the paused request to communicate with Serial
+static String message;
+static AsyncWebServerRequestPtr serialRequest;
+
+// request handler that is saved from the paused request to communicate with GPIO
+static uint8_t pin = 35;
+static AsyncWebServerRequestPtr gpioRequest;
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // Post a message that will be sent to the Serial console, and pause the request until the user types a key
+ //
+ // curl -v -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "question=Name%3F%20" http://192.168.4.1/serial
+ //
+ // curl output should show "Answer: [y/n]" as the response
+ server.on("/serial", HTTP_POST, [](AsyncWebServerRequest *request) {
+ message = request->getParam("question", true)->value();
+ serialRequest = request->pause();
+ });
+
+ // Wait for a GPIO to be high
+ //
+ // curl -v http://192.168.4.1/gpio
+ //
+ // curl output should show "GPIO is high!" as the response
+ server.on("/gpio", HTTP_GET, [](AsyncWebServerRequest *request) {
+ gpioRequest = request->pause();
+ });
+
+ pinMode(pin, INPUT);
+
+ server.begin();
+}
+
+void loop() {
+ delay(500);
+
+ // Check for a high voltage on the RX1 pin
+ if (digitalRead(pin) == HIGH) {
+ if (auto request = gpioRequest.lock()) {
+ request->send(200, "text/plain", "GPIO is high!");
+ }
+ }
+
+ // check for an incoming message from the Serial console
+ if (message.length()) {
+ Serial.printf("%s", message.c_str());
+ // drops buffer
+ while (Serial.available()) {
+ Serial.read();
+ }
+ Serial.setTimeout(10000);
+ String response = Serial.readStringUntil('\n'); // waits for a key to be pressed
+ Serial.println();
+ message = emptyString;
+ if (auto request = serialRequest.lock()) {
+ request->send(200, "text/plain", "Answer: " + response);
+ }
+ }
+}
diff --git a/examples/RequestContinuationComplete/RequestContinuationComplete.ino b/examples/RequestContinuationComplete/RequestContinuationComplete.ino
new file mode 100644
index 000000000..cb4a53fa4
--- /dev/null
+++ b/examples/RequestContinuationComplete/RequestContinuationComplete.ino
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Shows how to use request continuation to pause a request for a long processing task, and be able to resume it later.
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+#include
+#include
+#include
+
+static AsyncWebServer server(80);
+
+// ===============================================================
+// The code below is used to simulate some long running operations
+// ===============================================================
+
+typedef struct {
+ size_t id;
+ AsyncWebServerRequestPtr requestPtr;
+ uint8_t data;
+} LongRunningOperation;
+
+static std::list> longRunningOperations;
+static size_t longRunningOperationsCount = 0;
+#ifdef ESP32
+static std::mutex longRunningOperationsMutex;
+#endif
+
+static void startLongRunningOperation(AsyncWebServerRequestPtr &&requestPtr) {
+#ifdef ESP32
+ std::lock_guard lock(longRunningOperationsMutex);
+#endif
+
+ // LongRunningOperation *op = new LongRunningOperation();
+ std::unique_ptr op(new LongRunningOperation());
+ op->id = ++longRunningOperationsCount;
+ op->data = 10;
+
+ // you need to hold the AsyncWebServerRequestPtr returned by pause();
+ // This object is authorized to leave the scope of the request handler.
+ op->requestPtr = std::move(requestPtr);
+
+ Serial.printf("[%u] Start long running operation for %" PRIu8 " seconds...\n", op->id, op->data);
+ longRunningOperations.push_back(std::move(op));
+}
+
+static bool processLongRunningOperation(LongRunningOperation *op) {
+ // request was deleted ?
+ if (op->requestPtr.expired()) {
+ Serial.printf("[%u] Request was deleted - stopping long running operation\n", op->id);
+ return true; // operation finished
+ }
+
+ // processing the operation
+ Serial.printf("[%u] Long running operation processing... %" PRIu8 " seconds left\n", op->id, op->data);
+
+ // check if we have finished ?
+ op->data--;
+ if (op->data) {
+ // not finished yet
+ return false;
+ }
+
+ // Try to get access to the request pointer if it is still exist.
+ // If there has been a disconnection during that time, the pointer won't be valid anymore
+ if (auto request = op->requestPtr.lock()) {
+ Serial.printf("[%u] Long running operation finished! Sending back response...\n", op->id);
+ request->send(200, "text/plain", String(op->id) + " ");
+
+ } else {
+ Serial.printf("[%u] Long running operation finished, but request was deleted!\n", op->id);
+ }
+
+ return true; // operation finished
+}
+
+/// ==========================================================
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // Add a middleware to see how pausing a request affects the middleware chain
+ server.addMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) {
+ Serial.printf("Middleware chain start\n");
+
+ // continue to the next middleware, and at the end the request handler
+ next();
+
+ // we can check the request pause state after the handler was executed
+ if (request->isPaused()) {
+ Serial.printf("Request was paused!\n");
+ }
+
+ Serial.printf("Middleware chain ends\n");
+ });
+
+ // HOW TO RUN THIS EXAMPLE:
+ //
+ // 1. Open several terminals to trigger some requests concurrently that will be paused with:
+ // > time curl -v http://192.168.4.1/
+ //
+ // 2. Look at the output of the Serial console to see how the middleware chain is executed
+ // and to see the long running operations being processed and resume the requests.
+ //
+ // 3. You can try close your curl command to cancel the request and check that the request is deleted.
+ // Note: in case the network is disconnected, the request will be deleted.
+ //
+ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
+ // Print a message in case the request is disconnected (network disconnection, client close, etc.)
+ request->onDisconnect([]() {
+ Serial.printf("Request was disconnected!\n");
+ });
+
+ // Instruct ESPAsyncWebServer to pause the request and get a AsyncWebServerRequestPtr to be able to access the request later.
+ // The AsyncWebServerRequestPtr is the ONLY object authorized to leave the scope of the request handler.
+ // The Middleware chain will continue to run until the end after this handler exit, but the request will be paused and will not
+ // be sent to the client until send() is called later.
+ Serial.printf("Pausing request...\n");
+ AsyncWebServerRequestPtr requestPtr = request->pause();
+
+ // start our long operation...
+ startLongRunningOperation(std::move(requestPtr));
+ });
+
+ server.begin();
+}
+
+static uint32_t lastTime = 0;
+
+void loop() {
+ if (millis() - lastTime >= 1000) {
+
+#ifdef ESP32
+ Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap());
+ std::lock_guard lock(longRunningOperationsMutex);
+#endif
+
+ // process all long running operations
+ longRunningOperations.remove_if([](const std::unique_ptr &op) {
+ return processLongRunningOperation(op.get());
+ });
+
+ lastTime = millis();
+ }
+}
diff --git a/examples/ResumableDownload/ResumableDownload.ino b/examples/ResumableDownload/ResumableDownload.ino
new file mode 100644
index 000000000..68646e724
--- /dev/null
+++ b/examples/ResumableDownload/ResumableDownload.ino
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Make sure resumable downloads can be implemented (HEAD request / response and Range header)
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+static AsyncWebServer server(80);
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ /*
+ ❯ curl -I -X HEAD http://192.168.4.1/download
+ HTTP/1.1 200 OK
+ Content-Length: 1024
+ Content-Type: application/octet-stream
+ Connection: close
+ Accept-Ranges: bytes
+ */
+ // Ref: https://github.com/mathieucarbou/ESPAsyncWebServer/pull/80
+ server.on("/download", HTTP_HEAD | HTTP_GET, [](AsyncWebServerRequest *request) {
+ if (request->method() == HTTP_HEAD) {
+ AsyncWebServerResponse *response = request->beginResponse(200, "application/octet-stream");
+ response->addHeader(asyncsrv::T_Accept_Ranges, "bytes");
+ response->addHeader(asyncsrv::T_Content_Length, 10);
+ response->setContentLength(1024); // make sure we can overrides previously set content length
+ response->addHeader(asyncsrv::T_Content_Type, "foo");
+ response->setContentType("application/octet-stream"); // make sure we can overrides previously set content type
+ // ...
+ request->send(response);
+ } else {
+ // ...
+ }
+ });
+
+ server.begin();
+}
+
+void loop() {
+ delay(100);
+}
diff --git a/examples/Rewrite/Rewrite.ino b/examples/Rewrite/Rewrite.ino
new file mode 100644
index 000000000..8dfeedc67
--- /dev/null
+++ b/examples/Rewrite/Rewrite.ino
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
+
+//
+// Shows how to rewrite URLs
+//
+
+#include
+#if defined(ESP32) || defined(LIBRETINY)
+#include
+#include
+#elif defined(ESP8266)
+#include
+#include
+#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
+#include
+#include
+#endif
+
+#include
+
+static AsyncWebServer server(80);
+
+void setup() {
+ Serial.begin(115200);
+
+#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("esp-captive");
+#endif
+
+ // curl -v http://192.168.4.1/index.txt
+ server.on("/index.txt", HTTP_GET, [](AsyncWebServerRequest *request) {
+ request->send(200, "text/plain", "Hello, world!");
+ });
+
+ // curl -v http://192.168.4.1/index.txt
+ server.on("/index.html", HTTP_GET, [](AsyncWebServerRequest *request) {
+ request->send(200, "text/html", "