Коммит 6b2b7968 создал по автору OMP Education's avatar OMP Education Зафиксировано автором Elizaveta Vaysberg
Просмотр файлов

[Project] Implement Web App Server Application

владелец 5a997c2e
...@@ -5,5 +5,7 @@ ...@@ -5,5 +5,7 @@
* Konstantin Zvyagin, <k.zvyagin@omp.ru> * Konstantin Zvyagin, <k.zvyagin@omp.ru>
* Maintainer, 2025 * Maintainer, 2025
* Reviewer, 2025 * Reviewer, 2025
* Elizaveta Vaysberg <e.vaysberg@omp.ru>
* Reviewer, 2025
* Ivan Shchitov * Ivan Shchitov
* Developer, 2025 * Developer, 2025
# SPDX-FileCopyrightText: 2025 Open Mobile Platform LLC <community@omp.ru>
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.5) cmake_minimum_required(VERSION 3.5)
project(ru.auroraos.WebAppServer CXX) project(ru.auroraos.WebAppServer CXX)
...@@ -7,6 +10,9 @@ include(FindPkgConfig) ...@@ -7,6 +10,9 @@ include(FindPkgConfig)
pkg_search_module(AURORA auroraapp REQUIRED) pkg_search_module(AURORA auroraapp REQUIRED)
pkg_search_module(AURORA auroraapp_i18n REQUIRED) pkg_search_module(AURORA auroraapp_i18n REQUIRED)
find_package(PkgConfig REQUIRED)
pkg_check_modules(AuroraWebView aurorawebview IMPORTED_TARGET)
set(CMAKE_AUTOMOC ON) set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_INCLUDE_CURRENT_DIR ON)
...@@ -18,6 +24,8 @@ qt5_add_translation(QmFiles ${TsFiles}) ...@@ -18,6 +24,8 @@ qt5_add_translation(QmFiles ${TsFiles})
set(SOURCES set(SOURCES
src/main.cpp src/main.cpp
src/staticwebserverservice.h
src/staticwebserverservice.cpp
) )
set(CMAKE_SKIP_RPATH FALSE) set(CMAKE_SKIP_RPATH FALSE)
...@@ -34,6 +42,7 @@ target_include_directories(${PROJECT_NAME} PRIVATE ...@@ -34,6 +42,7 @@ target_include_directories(${PROJECT_NAME} PRIVATE
>) >)
target_link_libraries(${PROJECT_NAME} PRIVATE target_link_libraries(${PROJECT_NAME} PRIVATE
Qt5::Quick Qt5::Quick
PkgConfig::AuroraWebView
${AURORA_LDFLAGS} ${AURORA_LDFLAGS}
) )
...@@ -43,6 +52,12 @@ install(TARGETS ${PROJECT_NAME} ...@@ -43,6 +52,12 @@ install(TARGETS ${PROJECT_NAME}
install(DIRECTORY qml install(DIRECTORY qml
DESTINATION share/${PROJECT_NAME} DESTINATION share/${PROJECT_NAME}
) )
install(DIRECTORY initial-site
DESTINATION share/${PROJECT_NAME}
)
install(FILES libexec/${CMAKE_SYSTEM_PROCESSOR}/static-web-server
DESTINATION /usr/libexec/${PROJECT_NAME}
)
foreach(_file IN LISTS QmFiles) foreach(_file IN LISTS QmFiles)
get_filename_component(_filename "${_file}" NAME) get_filename_component(_filename "${_file}" NAME)
......
...@@ -79,5 +79,5 @@ please contact <community@omp.ru>. ...@@ -79,5 +79,5 @@ please contact <community@omp.ru>.
This work is licensed under a Creative Commons Attribution 3.0 Unported License This work is licensed under a Creative Commons Attribution 3.0 Unported License
For attribution requirements: For attribution requirements:
«Open Mobile Platform Code of Conduct» «Open Mobile Platform Code of Conduct»
Copyright (c) 2021 Open Mobile Platform LLC, Copyright (c) 2025 Open Mobile Platform LLC,
used under a [Creative Commons Attribution Unported license](http://creativecommons.org/licenses/by/3.0/). used under a [Creative Commons Attribution Unported license](http://creativecommons.org/licenses/by/3.0/).
...@@ -4,58 +4,77 @@ ...@@ -4,58 +4,77 @@
# WebAppServer # WebAppServer
Aurora OS application to demonstate how to start up local static web server and to display its content via WebView (Chromium). <a name="Description"></a>
## Description
This project provides an example application for browser usage.
The application demonstrates how to start up local static web server and to display its content via WebView (Chromium).
The application allows to:
- View web-content,
- View own static web-files.
The WebAppServer application uses the command-line utility [static-web-server](https://github.com/static-web-server/static-web-server) version [2.38.0](https://github.com/static-web-server/static-web-server/releases/tag/v2.38.0) to run a server for displaying static web-files. The `static-web-server` utility is distributed under [MIT license](https://github.com/static-web-server/static-web-server/blob/master/LICENSE-MIT) and [Apache License (Vesion 2.0)](https://github.com/static-web-server/static-web-server/blob/master/LICENSE-APACHE). The web files for the static web server must be located in the `~/Documents/WebAppServer/` directory on the device.
The application template is generated using the [WebAppGenerator](https://hub.mos.ru/auroraos/tools/WebAppGenerator) utility.
<a name="Table-of-contents"></a> <a name="Table-of-contents"></a>
## Table of Contents ## Table of contents
1. [Table of Contents](#Table-of-contents) 1. [Compatibility](#Compatibility)
2. [Compatibility](#Compatibility) 2. [Build features](#Build-features)
3. [Features of use and build](#Features-of-use-and-build) 3. [Branches info](#Branches-info)
4. [Branch info](#Branch-info) 4. [Install and run](#Install-and-run)
5. [Install and Run](#Install-and-Run) 5. [Screenshots](#Screenshots)
6. [Screenshots](#Screenshots) 6. [Use cases](#Use-cases)
7. [Use cases](#Use-cases) 7. [Known errors and restrictions](#Known-errors-and-restrictions)
8. [Known errors](#Known-errors) 8. [Project structure](#Project-structure)
9. [Project Structure](#Project-structure) 9. [Terms of use and participation in development](#Terms-of-use-and-participation-in-development)
10. [Terms of Use and Participation in Development](#Terms-of-use-and-participation-in-development)
<a name="Compatibility"></a> <a name="Compatibility"></a>
## Compatibility ## Compatibility
The application is working correctly since 5.1.3.45 version of Aurora OS. The application is working correctly since 5.1.3.45 version of Aurora OS.
<a name="Features-of-use-and-build"></a> <a name="Build-features"></a>
## Features of use and build ## Build features
This example being built using the Aurora SDK: [Documentation](https://developer.auroraos.ru/doc/5.1.4/sdk/app_development/work/create/examples#build) This example being built using the Aurora SDK: [Documentation](https://developer.auroraos.ru/doc/sdk/app_development/work/create/examples#build)
<a name="Branch-info"></a> <a name="Branches-info"></a>
## Branch info ## Branches info
[Branches](https://developer.auroraos.ru/doc/5.1.3/software_development/examples#branches) [Branches](https://developer.auroraos.ru/doc/software_development/examples#branches)
<a name="Install-and-Run"></a> <a name="Install-and-run"></a>
## Install and Run ## Install and run
The project being built in the usual way using the Aurora SDK: [Documentation](https://developer.auroraos.ru/doc/5.1.3/sdk/app_development/work/build). The project being built in the usual way using the Aurora SDK: [Documentation](https://developer.auroraos.ru/doc/sdk/app_development/work/build).
<a name="Screenshots"></a> <a name="Screenshots"></a>
## Screenshots ## Screenshots
// TODO ![Screenshots](screenshots/screenshots.png)
![screenshots](screenshots/screenshots_en.png)
<a name="Use-cases"></a> <a name="Use-cases"></a>
## Use cases ## Use cases
// TODO ### Viewing web-content
<a name="Known-errors"></a> * Run the application to view the web content.
## Known errors * When the application starts, the static web server will be running and its contents will be displayed in a Chromium-based WebView.
* By default, the main page will contain a message on how to configure the own static web files to display.
// TODO ### Setting up the display of own web-files
* To display own static web files, place them to the `~/Documents/WebAppServer/` device directory and restart the application.
* When the application starts, the directory `~/Documents/WebAppServer/` will be created if it was not created earlier.
<a name="Known-errors-and-restrictions"></a>
## Known errors and restrictions
No known errors have been found in the project.
<a name="Project-structure"></a> <a name="Project-structure"></a>
## Project structure ## Project structure
...@@ -66,11 +85,13 @@ of an application based on C++ and QML for Aurora OS. ...@@ -66,11 +85,13 @@ of an application based on C++ and QML for Aurora OS.
* **[CMakeLists.txt](CMakeLists.txt)** file * **[CMakeLists.txt](CMakeLists.txt)** file
describes the project structure for the CMake build system. describes the project structure for the CMake build system.
* **[icons](icons)** directory contains application icons for different screen resolutions. * **[icons](icons)** directory contains application icons for different screen resolutions.
* **[initial-site](initial-site)** directory contains the HTML-file with default web page to demonstrate the app.
* **[libexec](libexec)** directory contains the static-web-server binary files for 3 available architectures: aarch64, armv7l и x86_64.
* **[qml](qml)** directory contains the QML source code and the UI resources. * **[qml](qml)** directory contains the QML source code and the UI resources.
* **[cover](qml/cover)** directory contains the application cover implementations. * **[cover](qml/cover)** directory contains the application cover implementations.
* **[icons](qml/icons)** directory contains the custom UI icons. * **[icons](qml/icons)** directory contains the custom UI icons.
* **[pages](qml/pages)** directory contains the application pages. * **[pages](qml/pages)** directory contains the application pages.
* **[WebAppServer.qml](qml/WebAppServer.qml)** file * **[ru.auroraos.WebAppServer.qml](qml/ru.auroraos.WebAppServer.qml)** file
provides the application window implementation. provides the application window implementation.
* **[rpm](rpm)** directory contains the rpm-package build settings. * **[rpm](rpm)** directory contains the rpm-package build settings.
* **[ru.auroraos.WebAppServer.spec](rpm/ru.auroraos.WebAppServer.spec)** file is used by rpmbuild tool. * **[ru.auroraos.WebAppServer.spec](rpm/ru.auroraos.WebAppServer.spec)** file is used by rpmbuild tool.
...@@ -80,20 +101,18 @@ of an application based on C++ and QML for Aurora OS. ...@@ -80,20 +101,18 @@ of an application based on C++ and QML for Aurora OS.
* **[ru.auroraos.WebAppServer.desktop](ru.auroraos.WebAppServer.desktop)** file * **[ru.auroraos.WebAppServer.desktop](ru.auroraos.WebAppServer.desktop)** file
defines the display and parameters for launching the application. defines the display and parameters for launching the application.
<a name="Terms-of-use-and-participation-in-development"></a> <a name="Terms-of-use-and-participation-in-development"></a>
## Terms of Use and Participation in Development ## Terms of use and participation in development
The source code of the project is provided under [the license](LICENSE.BSD-3-CLAUSE.md), The source code of the project is provided under [the license](LICENSE.BSD-3-Clause.md),
which allows it to be used in third-party applications. which allows its use in third-party applications.
[Contributor License Agreement](https://gitlab.com/omprussia/wiki/-/wikis/CLA) [Contributor License Agreement](https://gitlab.com/omprussia/wiki/-/wikis/CLA)
The [contributor agreement](CONTRIBUTING.md) documents the rights granted by contributors The [contributor agreement](CONTRIBUTING.md) documents the rights granted by contributors
of the Open Mobile Platform. of the Open Mobile Platform.
Information about the contributors is specified in the [AUTHORS](AUTHORS.md) file. Information about the contributors is specified in the [AUTHORS](AUTHORS.md) file.
[Code of conduct](https://gitlab.com/omprussia/wiki/-/wikis/Code_of_Conduct) is a current set of rules of the Open Mobile [Code of conduct](CODE_OF_CONDUCT.md) is a current set of rules of the Open Mobile
Platform which informs you how we expect the members of the community will interact Platform which informs you how we expect the members of the community will interact
while contributing and communicating. while contributing and communicating.
...@@ -4,58 +4,77 @@ ...@@ -4,58 +4,77 @@
# WebAppServer # WebAppServer
Приложение для демонтрации запуска локального статического веб-сервера и отображения его контента с помощью WebView (Chromium) на ОС Аврора. <a name="Описание"></a>
## Описание
<a name="Cодержание"></a> Проект предоставляет приложение-пример по использованию браузера.
Приложение для демонcтрации запуска локального статического веб-сервера и отображения его контента с помощью WebView (Chromium) на ОС Аврора.
Приложение позволяет:
- Просмотривать веб-содержимое,
- Просматривать собственные статические веб-файлы.
Приложение WebAppServer использует утилиту командной строки [static-web-server](https://github.com/static-web-server/static-web-server) версии [2.38.0](https://github.com/static-web-server/static-web-server/releases/tag/v2.38.0) для запуска сервера для отображения статических веб-файлов. Утилита `static-web-server` распространяется под лицензиями [MIT license](https://github.com/static-web-server/static-web-server/blob/master/LICENSE-MIT) и [Apache License (Vesion 2.0)](https://github.com/static-web-server/static-web-server/blob/master/LICENSE-APACHE). Веб-файлы для статического веб-сервера должны располагаться в каталоге `~/Documents/WebAppServer/` на устройстве.
Шаблон приложения сгенерирован с помощью утилиты [WebAppGenerator](https://hub.mos.ru/auroraos/tools/WebAppGenerator).
<a name="Содержание"></a>
## Содержание ## Содержание
1. [Содержание](#Cодержание) 1. [Совместимость](#Совместимость)
2. [Совместимость](#Совместимость) 2. [Особенности сборки](#Особенности-сборки)
3. [Особенности использования и сборки](#Особенности-использования-и-сборки) 3. [Информация о ветках](#Информация-о-ветках)
4. [Информация о ветках](#Информация-о-ветках) 4. [Установка и запуск](#Установка-и-запуск)
5. [Установка и запуск](#Установка-и-запуск) 5. [Скриншоты](#Скриншоты)
6. [Скриншоты](#Скриншоты) 6. [Варианты использования](#Варианты-использования)
7. [Варианты использования](#Варианты-использования) 7. [Известные ошибки и ограничения](#Известные-ошибки-и-ограничения)
8. [Известные ошибки](#Известные-ошибки) 8. [Структура проекта](#Структура-проекта)
9. [Структура проекта](#Структура-проекта) 9. [Правила использования и участие в разработке](#Правила-использования-и-участие-в-разработке)
10. [Правила использования и участие в разработке](#Правила-использования-и-участие-в-разработке)
<a name="Совместимость"></a> <a name="Совместимость"></a>
## Совместимость ## Совместимость
Приложение корректно работает начиная с 5.1.3.45 версии ОС Авроры Приложение корректно работает, начиная с 5.1.3.45 версии ОС Авроры
<a name="Особенности-использования-и-сборки"></a> <a name="Особенности-сборки"></a>
## Особенности использования и сборки ## Особенности сборки
Данный пример-приложение собирается с помощью Аврора SDK: [Документация](https://developer.auroraos.ru/doc/5.1.4/sdk/app_development/work/create/examples#build) Данный пример-приложение собирается с помощью Аврора SDK: [Документация](https://developer.auroraos.ru/doc/sdk/app_development/work/create/examples#build)
<a name="Информация-о-ветках"></a> <a name="Информация-о-ветках"></a>
## Информация о ветках ## Информация о ветках
[Ветки](https://developer.auroraos.ru/doc/5.1.3/software_development/examples#branches) [Ветки](https://developer.auroraos.ru/doc/software_development/examples#branches)
<a name="Установка-и-запуск"></a> <a name="Установка-и-запуск"></a>
## Установка и запуск ## Установка и запуск
Проект собирается обычным образом с помощью Аврора SDK: [Документация](https://developer.auroraos.ru/doc/5.1.3/sdk/app_development/work/build). Проект собирается обычным образом с помощью Аврора SDK: [Документация](https://developer.auroraos.ru/doc/sdk/app_development/work/build).
<a name="Скриншоты"></a> <a name="Скриншоты"></a>
## Снимки экранов ## Скриншоты
// TODO ![Screenshots](screenshots/screenshots.png)
![screenshots](screenshots/screenshots_ru.png)
<a name="Варианты-использования"></a> <a name="Варианты-использования"></a>
## Варианты использования ## Варианты использования
// TODO ### Просмотр веб-содержимого
* Для просмотра веб-содержимого необходимо выполнить запуск приложения.
* При старте приложения будет запущен статический веб-сервер и отображено его содержимое в WebView на базе Chromium.
* По умолчанию будет отображена страница с сообщением о том, как настроить отображение собственных статических веб-файлов.
### Настройка отображения собственных веб-файлов
* Для отображения собственных статических веб-файлов необходимо поместить их в каталог `~/Documents/WebAppServer/` на устройстве и перезапустить приложение.
* При старте приложения каталог `~/Documents/WebAppServer/` будет создан, если он не был создан ранее.
<a name="Известные-ошибки"></a> <a name="Известные-ошибки-и-ограничения"></a>
## Известные ошибки ## Известные ошибки и ограничения
// TODO В проекте не обнаружены известные ошибки.
<a name="Структура-проекта"></a> <a name="Структура-проекта"></a>
## Структура проекта ## Структура проекта
...@@ -65,11 +84,13 @@ ...@@ -65,11 +84,13 @@
* Файл **[CMakeLists.txt](CMakeLists.txt)** * Файл **[CMakeLists.txt](CMakeLists.txt)**
описывает структуру проекта для системы сборки CMake. описывает структуру проекта для системы сборки CMake.
* Каталог **[icons](icons)** содержит иконки приложения для поддерживаемых разрешений экрана. * Каталог **[icons](icons)** содержит иконки приложения для поддерживаемых разрешений экрана.
* Каталог **[initial-site](initial-site)** содержит HTML-файл с веб-страницей по умолчанию для демонстрации.
* Каталог **[libexec](libexec)** содержит бинарные файлы static-web-server для трёх доступных архитектур: aarch64, armv7l и x86_64.
* Каталог **[qml](qml)** содержит исходный код на QML и ресурсы интерфейса пользователя. * Каталог **[qml](qml)** содержит исходный код на QML и ресурсы интерфейса пользователя.
* Каталог **[cover](qml/cover)** содержит реализации обложек приложения. * Каталог **[cover](qml/cover)** содержит реализации обложек приложения.
* Каталог **[icons](qml/icons)** содержит дополнительные иконки интерфейса пользователя. * Каталог **[icons](qml/icons)** содержит дополнительные иконки интерфейса пользователя.
* Каталог **[pages](qml/pages)** содержит страницы приложения. * Каталог **[pages](qml/pages)** содержит страницы приложения.
* Файл **[WebAppServer.qml](qml/WebAppServer.qml)** * Файл **[ru.auroraos.WebAppServer.qml](qml/ru.auroraos.WebAppServer.qml)**
предоставляет реализацию окна приложения. предоставляет реализацию окна приложения.
* Каталог **[rpm](rpm)** содержит настройки сборки rpm-пакета. * Каталог **[rpm](rpm)** содержит настройки сборки rpm-пакета.
* Файл **[ru.auroraos.WebAppServer.spec](rpm/ru.auroraos.WebAppServer.spec)** используется инструментом rpmbuild. * Файл **[ru.auroraos.WebAppServer.spec](rpm/ru.auroraos.WebAppServer.spec)** используется инструментом rpmbuild.
...@@ -82,15 +103,15 @@ ...@@ -82,15 +103,15 @@
<a name="Правила-использования-и-участие-в-разработке"></a> <a name="Правила-использования-и-участие-в-разработке"></a>
## Правила использования и участие в разработке ## Правила использования и участие в разработке
Исходный код проекта предоставляется по [лицензии](LICENSE.BSD-3-CLAUSE.md), Исходный код проекта предоставляется по [лицензии](LICENSE.BSD-3-Clause.md),
которая позволяет использовать его в сторонних приложениях. которая позволяет использовать его в сторонних приложениях.
[Лицензионное соглашение с участником](https://gitlab.com/omprussia/wiki/-/wikis/CLA.ru) [Лицензионное соглашение с участником](https://gitlab.com/omprussia/wiki/-/wikis/CLA.ru)
[Соглашение участника](CONTRIBUTING.md) регламентирует права, [Соглашение участника](CONTRIBUTING.md) регламентирует права,
предоставляемые участниками компании «Открытая Мобильная Платформа». предоставляемые участниками компании «Открытая Мобильная Платформа».
Информация об участниках указана в файле [AUTHORS](AUTHORS.md). Информация об участниках указана в файле [AUTHORS](AUTHORS.md).
[Кодекс поведения](https://gitlab.com/omprussia/wiki/-/wikis/Code_of_Conduct.ru) — это действующий набор правил [Кодекс поведения](CODE_OF_CONDUCT.md) — это действующий набор правил
компании «Открытая Мобильная Платформа», компании «Открытая Мобильная Платформа»,
который информирует об ожиданиях по взаимодействию между членами сообщества при общении и работе над проектами. который информирует об ожиданиях по взаимодействию между членами сообщества при общении и работе над проектами.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>
Страница по умолчанию — WebAppServer
</title>
<style>
p { font-size: 24px; }
</style>
</head>
<body>
<p>Это веб-страница по умолчанию для отображения в примере WebAppServer.</p>
<p>Чтобы использовать собственные статические веб-файлы, Вам необходимо поместить их в каталог ~/Documents/WebAppServer/ на устройстве.</p>
</body>
</html>
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
The MIT License (MIT)
Copyright (c) 2019-present Jose Quintana <https://joseluisq.net>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<div>
<div align="center">
<a href="https://static-web-server.net" title="static-web-server website">
<img src="https://static-web-server.net/assets/sws.svg" height="100" width="100"
/></a>
</div>
<h1 align="center">Static Web Server</h1>
<h4 align="center">
A cross-platform, high-performance and asynchronous web server for static files-serving ⚡
</h4>
<div align="center">
<a href="https://github.com/static-web-server/static-web-server/actions/workflows/devel.yml" title="devel ci"><img src="https://github.com/static-web-server/static-web-server/actions/workflows/devel.yml/badge.svg?branch=master"></a>
<a href="https://hub.docker.com/r/joseluisq/static-web-server/" title="Docker Image Version (tag latest semver)"><img src="https://img.shields.io/docker/v/joseluisq/static-web-server/2"></a>
<a href="https://hub.docker.com/r/joseluisq/static-web-server/tags" title="Docker Image Size (tag)"><img src="https://img.shields.io/docker/image-size/joseluisq/static-web-server/2"></a>
<a href="https://hub.docker.com/r/joseluisq/static-web-server/" title="Docker Image"><img src="https://img.shields.io/docker/pulls/joseluisq/static-web-server.svg"></a>
<a href="https://crates.io/crates/static-web-server" title="static-web-server crate"><img src="https://img.shields.io/crates/v/static-web-server.svg"></a>
<a href="https://docs.rs/static-web-server" title="static-web-server crate docs"><img src="https://img.shields.io/docsrs/static-web-server/latest?label=docs.rs"></a>
<a href="https://github.com/static-web-server/static-web-server/blob/master/LICENSE-APACHE" title="static-web-server license"><img src="https://img.shields.io/crates/l/static-web-server"></a>
<a href="https://discord.gg/VWvtZeWAA7" title="Static Web Server Community on Discord">
<img src="https://img.shields.io/discord/1086203405225164842?logo=discord&label=discord">
</a>
</div>
</div>
## Overview
**Static Web Server** (or **`SWS`** abbreviated) is a tiny and fast production-ready web server suitable to serve static web files or assets.
It is focused on **lightness and easy-to-use** principles while keeping [high performance and safety](https://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html) powered by [The Rust Programming Language](https://rust-lang.org).
Written on top of [Hyper](https://github.com/hyperium/hyper) and [Tokio](https://github.com/tokio-rs/tokio) runtime, it provides [concurrent and asynchronous networking abilities](https://rust-lang.github.io/async-book/01_getting_started/02_why_async.html) and the latest HTTP/1 - HTTP/2 implementations.
Cross-platform and available for `Linux`, `macOS`, `Windows`, `FreeBSD`, `NetBSD`, `Android`, `Docker` and `Wasm` (via [Wasmer](https://wasmer.io/wasmer/static-web-server)).
![static-web-server running](https://github.com/static-web-server/static-web-server/assets/1700322/102bef12-1f30-4054-a1bc-30c650d4ffa7)
## Features
- Built with [Rust](https://rust-lang.org), which focuses on [safety, speed and concurrency](https://kornel.ski/rust-c-speed).
- Memory-safe and significantly reduced CPU and RAM overhead.
- Blazing fast static files-serving and asynchronous powered by the latest [Hyper](https://github.com/hyperium/hyper/), [Tokio](https://github.com/tokio-rs/tokio) and a set of [awesome crates](https://github.com/static-web-server/static-web-server/blob/master/Cargo.toml).
- Single __4MB__ (uncompressed) and fully static binary with no dependencies ([Musl libc](https://doc.rust-lang.org/edition-guide/rust-2018/platform-and-target-support/musl-support-for-fully-static-binaries.html)). Suitable for running on [any Linux distro](https://en.wikipedia.org/wiki/Linux_distribution) or [Docker container](https://hub.docker.com/r/joseluisq/static-web-server/tags).
- Optional GZip, Deflate, Brotli or Zstandard (zstd) compression for text-based web files only.
- Compression on-demand via [Accept-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding) header.
- [Partial Content Delivery](https://en.wikipedia.org/wiki/Byte_serving) support for byte-serving of large files.
- Optional [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) headers for assets.
- [Termination signal](https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html) handling with [graceful shutdown](https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace) ability and grace period.
- [HTTP/2](https://tools.ietf.org/html/rfc7540) and TLS support.
- [Security headers](https://web.dev/security-headers/) for HTTP/2 by default.
- [HEAD](https://tools.ietf.org/html/rfc7231#section-4.3.2) and [OPTIONS](https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.7) responses.
- Lightweight and configurable logging via [tracing](https://github.com/tokio-rs/tracing) crate.
- Customizable number of blocking and worker threads.
- Optional directory listing with sorting and JSON output format support.
- [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) with preflight requests support.
- Basic HTTP Authentication.
- Customizable HTTP response headers for specific file requests via glob patterns.
- Fallback pages for 404 errors, useful for Single-page applications.
- Run the server as a [Windows Service](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc783643(v=ws.10)).
- Configurable using CLI arguments, environment variables or a TOML file.
- Default and custom error pages.
- Built-in HTTP to HTTPS redirect.
- GET/HEAD Health check endpoint.
- Support for serving pre-compressed (Gzip/Brotli/Zstd) files directly from disk.
- Custom URL rewrites and redirects via glob patterns with replacements.
- Virtual hosting support.
- Multiple index files.
- Maintenance Mode functionality.
- Available as a library crate with opt-in features.
- First-class [Docker](https://docs.docker.com/get-started/overview/) support. [Scratch](https://hub.docker.com/_/scratch), latest [Alpine Linux](https://hub.docker.com/_/alpine) and [Debian](https://hub.docker.com/_/alpine) Docker images.
- Ability to accept a socket listener as a file descriptor for sandboxing and on-demand applications (e.g. [systemd](http://0pointer.de/blog/projects/socket-activation.html)).
- Cross-platform. Pre-compiled binaries for Linux, macOS, Windows, FreeBSD, NetBSD, Android (`x86/x86_64`, `ARM/ARM64`) and WebAssembly (via [Wasmer](https://wasmer.io/wasmer/static-web-server)).
## Documentation
Please refer to [The Documentation Website](https://static-web-server.net/) for more details about the API, usage and examples.
## Releases
- [Docker Images](https://hub.docker.com/r/joseluisq/static-web-server/)
- [Release Binaries](https://github.com/static-web-server/static-web-server/releases)
- [Platforms/Architectures Supported](https://static-web-server.net/platforms-architectures/)
## Benchmarks
<img title="SWS - Benchmarks April 2023" src="https://raw.githubusercontent.com/static-web-server/benchmarks/master/data/2023-04/benchmark-2023-04.png" width="860">
For more details see [benchmarks repository](https://github.com/static-web-server/benchmarks)
## Notes
- If you're looking for `v1` please go to [1.x](https://github.com/static-web-server/static-web-server/tree/1.x) branch.
- If you want to migrate from `v1` to `v2` please view [Migrating from `v1` to `v2`](https://static-web-server.net/migration/) release.
## Contributions
Unless you explicitly state otherwise, any contribution you intentionally submitted for inclusion in current work, as defined in the Apache-2.0 license, shall be dual licensed as described below, without any additional terms or conditions.
Feel free to submit a [pull request](https://github.com/static-web-server/static-web-server/pulls) or file an [issue](https://github.com/static-web-server/static-web-server/issues).
## Community
[SWS Community on Discord](https://discord.gg/VWvtZeWAA7)
## License
This work is primarily distributed under the terms of both the [MIT license](LICENSE-MIT) and the [Apache License (Version 2.0)](LICENSE-APACHE).
© 2019-present [Jose Quintana](https://joseluisq.net)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
The MIT License (MIT)
Copyright (c) 2019-present Jose Quintana <https://joseluisq.net>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<div>
<div align="center">
<a href="https://static-web-server.net" title="static-web-server website">
<img src="https://static-web-server.net/assets/sws.svg" height="100" width="100"
/></a>
</div>
<h1 align="center">Static Web Server</h1>
<h4 align="center">
A cross-platform, high-performance and asynchronous web server for static files-serving ⚡
</h4>
<div align="center">
<a href="https://github.com/static-web-server/static-web-server/actions/workflows/devel.yml" title="devel ci"><img src="https://github.com/static-web-server/static-web-server/actions/workflows/devel.yml/badge.svg?branch=master"></a>
<a href="https://hub.docker.com/r/joseluisq/static-web-server/" title="Docker Image Version (tag latest semver)"><img src="https://img.shields.io/docker/v/joseluisq/static-web-server/2"></a>
<a href="https://hub.docker.com/r/joseluisq/static-web-server/tags" title="Docker Image Size (tag)"><img src="https://img.shields.io/docker/image-size/joseluisq/static-web-server/2"></a>
<a href="https://hub.docker.com/r/joseluisq/static-web-server/" title="Docker Image"><img src="https://img.shields.io/docker/pulls/joseluisq/static-web-server.svg"></a>
<a href="https://crates.io/crates/static-web-server" title="static-web-server crate"><img src="https://img.shields.io/crates/v/static-web-server.svg"></a>
<a href="https://docs.rs/static-web-server" title="static-web-server crate docs"><img src="https://img.shields.io/docsrs/static-web-server/latest?label=docs.rs"></a>
<a href="https://github.com/static-web-server/static-web-server/blob/master/LICENSE-APACHE" title="static-web-server license"><img src="https://img.shields.io/crates/l/static-web-server"></a>
<a href="https://discord.gg/VWvtZeWAA7" title="Static Web Server Community on Discord">
<img src="https://img.shields.io/discord/1086203405225164842?logo=discord&label=discord">
</a>
</div>
</div>
## Overview
**Static Web Server** (or **`SWS`** abbreviated) is a tiny and fast production-ready web server suitable to serve static web files or assets.
It is focused on **lightness and easy-to-use** principles while keeping [high performance and safety](https://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html) powered by [The Rust Programming Language](https://rust-lang.org).
Written on top of [Hyper](https://github.com/hyperium/hyper) and [Tokio](https://github.com/tokio-rs/tokio) runtime, it provides [concurrent and asynchronous networking abilities](https://rust-lang.github.io/async-book/01_getting_started/02_why_async.html) and the latest HTTP/1 - HTTP/2 implementations.
Cross-platform and available for `Linux`, `macOS`, `Windows`, `FreeBSD`, `NetBSD`, `Android`, `Docker` and `Wasm` (via [Wasmer](https://wasmer.io/wasmer/static-web-server)).
![static-web-server running](https://github.com/static-web-server/static-web-server/assets/1700322/102bef12-1f30-4054-a1bc-30c650d4ffa7)
## Features
- Built with [Rust](https://rust-lang.org), which focuses on [safety, speed and concurrency](https://kornel.ski/rust-c-speed).
- Memory-safe and significantly reduced CPU and RAM overhead.
- Blazing fast static files-serving and asynchronous powered by the latest [Hyper](https://github.com/hyperium/hyper/), [Tokio](https://github.com/tokio-rs/tokio) and a set of [awesome crates](https://github.com/static-web-server/static-web-server/blob/master/Cargo.toml).
- Single __4MB__ (uncompressed) and fully static binary with no dependencies ([Musl libc](https://doc.rust-lang.org/edition-guide/rust-2018/platform-and-target-support/musl-support-for-fully-static-binaries.html)). Suitable for running on [any Linux distro](https://en.wikipedia.org/wiki/Linux_distribution) or [Docker container](https://hub.docker.com/r/joseluisq/static-web-server/tags).
- Optional GZip, Deflate, Brotli or Zstandard (zstd) compression for text-based web files only.
- Compression on-demand via [Accept-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding) header.
- [Partial Content Delivery](https://en.wikipedia.org/wiki/Byte_serving) support for byte-serving of large files.
- Optional [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) headers for assets.
- [Termination signal](https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html) handling with [graceful shutdown](https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace) ability and grace period.
- [HTTP/2](https://tools.ietf.org/html/rfc7540) and TLS support.
- [Security headers](https://web.dev/security-headers/) for HTTP/2 by default.
- [HEAD](https://tools.ietf.org/html/rfc7231#section-4.3.2) and [OPTIONS](https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.7) responses.
- Lightweight and configurable logging via [tracing](https://github.com/tokio-rs/tracing) crate.
- Customizable number of blocking and worker threads.
- Optional directory listing with sorting and JSON output format support.
- [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) with preflight requests support.
- Basic HTTP Authentication.
- Customizable HTTP response headers for specific file requests via glob patterns.
- Fallback pages for 404 errors, useful for Single-page applications.
- Run the server as a [Windows Service](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc783643(v=ws.10)).
- Configurable using CLI arguments, environment variables or a TOML file.
- Default and custom error pages.
- Built-in HTTP to HTTPS redirect.
- GET/HEAD Health check endpoint.
- Support for serving pre-compressed (Gzip/Brotli/Zstd) files directly from disk.
- Custom URL rewrites and redirects via glob patterns with replacements.
- Virtual hosting support.
- Multiple index files.
- Maintenance Mode functionality.
- Available as a library crate with opt-in features.
- First-class [Docker](https://docs.docker.com/get-started/overview/) support. [Scratch](https://hub.docker.com/_/scratch), latest [Alpine Linux](https://hub.docker.com/_/alpine) and [Debian](https://hub.docker.com/_/alpine) Docker images.
- Ability to accept a socket listener as a file descriptor for sandboxing and on-demand applications (e.g. [systemd](http://0pointer.de/blog/projects/socket-activation.html)).
- Cross-platform. Pre-compiled binaries for Linux, macOS, Windows, FreeBSD, NetBSD, Android (`x86/x86_64`, `ARM/ARM64`) and WebAssembly (via [Wasmer](https://wasmer.io/wasmer/static-web-server)).
## Documentation
Please refer to [The Documentation Website](https://static-web-server.net/) for more details about the API, usage and examples.
## Releases
- [Docker Images](https://hub.docker.com/r/joseluisq/static-web-server/)
- [Release Binaries](https://github.com/static-web-server/static-web-server/releases)
- [Platforms/Architectures Supported](https://static-web-server.net/platforms-architectures/)
## Benchmarks
<img title="SWS - Benchmarks April 2023" src="https://raw.githubusercontent.com/static-web-server/benchmarks/master/data/2023-04/benchmark-2023-04.png" width="860">
For more details see [benchmarks repository](https://github.com/static-web-server/benchmarks)
## Notes
- If you're looking for `v1` please go to [1.x](https://github.com/static-web-server/static-web-server/tree/1.x) branch.
- If you want to migrate from `v1` to `v2` please view [Migrating from `v1` to `v2`](https://static-web-server.net/migration/) release.
## Contributions
Unless you explicitly state otherwise, any contribution you intentionally submitted for inclusion in current work, as defined in the Apache-2.0 license, shall be dual licensed as described below, without any additional terms or conditions.
Feel free to submit a [pull request](https://github.com/static-web-server/static-web-server/pulls) or file an [issue](https://github.com/static-web-server/static-web-server/issues).
## Community
[SWS Community on Discord](https://discord.gg/VWvtZeWAA7)
## License
This work is primarily distributed under the terms of both the [MIT license](LICENSE-MIT) and the [Apache License (Version 2.0)](LICENSE-APACHE).
© 2019-present [Jose Quintana](https://joseluisq.net)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
The MIT License (MIT)
Copyright (c) 2019-present Jose Quintana <https://joseluisq.net>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать