Commit 32548c88 authored by Mathieu Stefani's avatar Mathieu Stefani

Merge branch 'master' into server-client-request-timeout

parents ccfd4a3c 0d09ab98
---
name: Bug report
about: Create a report to help us improve
title: "[BUG] (Insert short description)"
labels: ''
assignees: ''
---
## Current Behavior
## Expected behavior
## Possible Solution
## Steps to reproduce the bug
## Context (Environment)
- Pistache version: major.minor.patch-git_revision
- Operating System: (Distro and release)
- Architecture: (amd64, arm64, armhf, i386, ppc64el, s390x, all, or other)
- Installed from: (Built from source / unstable or stable PPA)
- Used `pkg-config`: (yes / no)
Screenshots, logs, stacktraces or other relevant information here.
blank_issues_enabled: false
---
name: Feature request
about: Suggest an idea for this project
title: "[FEATURE REQUEST] (Insert a short description)"
labels: enhancement
assignees: ''
---
## Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] or it would be great if Pistache could do [...].
## Describe the solution you'd like
A clear and concise description of what you want to happen.
## Additional Context
Add any other context or screenshots about the feature request here.
(Provide a general summary of your changes in the Title above.)
## Description
(Describe your changes in detail)
## Related Issue
Fixes: #.
## Motivation and Context
(Why is this change required? What problem does it solve?)
## Versioning Changes
- I read the _Interface Versioning_ section in `README.md`: (yes / no)
- Interface version was changed: (yes / no)
- Release version was changed: (yes / no)
## Unit and CI Testing
- Operating System: (Distro and release)
- Architectures Tested: (amd64, arm64, armhf, i386, ppc64el, s390x, all, other)
- I read the _Continuous Integration_ section in `README.md`: (yes / no)
- Changes introduced new or an alteration to an existing test: (yes / no)
- All in-tree unit tests pass: (yes / no)
- All DEP-8 CI tests pass: (yes / no)
## Screenshots: (if appropriate)
name: pistache.io
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
pistacheio-deploy:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- name: Install dependencies
run: |
sudo apt-get update && sudo apt-get install -qq npm --no-install-recommends --assume-yes
sudo npm install --global --silent yarn
sudo npm install --global --force --silent npx
- name: Build docs site
run: |
cd pistache.io
yarn install --non-interactive
yarn build
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./pistache.io/build
cname: pistache.io
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>404 Page Not Found</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Pistache is a C++ REST framework focussed on high performance and clear API. Pistache is a free software written by Mathieu Stefani and available on Github - https://github.com/oktal/pistache
">
<link rel="canonical"
href="http://pistache.io/404.html">
<!-- Harmony styles -->
<link rel="stylesheet" type="text/css" href="/assets/css/main.css">
<!-- Modernizr js -->
<script async src="/assets/js/modernizr.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.min.css" />
<!--[if lt IE 9]>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.ie.min.css" />
<![endif]-->
<!-- IE Fixes -->
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="theme-base-01">
<header class="main-header">
<div class="wc-container">
<img id="img-logo" src="/assets/images/logo.png" />
<h1>
<a href="/">Pistache</a>
</h1>
<h2>An elegant C++ REST framework.</h2>
<ul>
<li>
<a href="/">Pistache</a><span>/</span>
</li>
<li>
<a href="/quickstart">Getting Started</a><span>/</span>
</li>
<li>
<a href="/guide/">User's Guide</a><span>/</span>
</li>
<li>
<a title="Pistache on Github"
href="https://github.com/oktal/pistache" target="_blank">
Source code
</a><span>/</span>
</li>
</ul>
<div style="text-align: center">
<iframe src="https://ghbtns.com/github-btn.html?user=oktal&repo=pistache&type=star&count=true&size=large" frameborder="0" scrolling="0" width="160px" height="30px"></iframe>
<iframe src="https://ghbtns.com/github-btn.html?user=oktal&repo=pistache&type=fork&count=true&size=large" frameborder="0" scrolling="0" width="158px" height="30px"></iframe>
</div>
</div>
</header>
<div class="page-content wc-container">
<h3>404 Page Not Found</h3>
<h4>The page you were looking for is not found.</h4>
<p>Sorry, we've misplaced that URL or it's pointing to something that
doesn't exist. Please <a href="">head back home</a> to try finding it again.</p>
</div>
<footer class="main-footer">
<div class="wc-container">
<div class="column one">
<h6>Few more links</h6>
<ul class="menu">
</ul>
</div>
<div class="column two">
<h6>Follow me</h6>
<ul class="social-media">
<li>
<a title="oktal on Github"
href="https://github.com/oktal"
class="github wc-img-replace" target="_blank">Github</a>
</li>
</ul>
</div>
</div>
<p class="wc-container disclaimer">
Powered by <a href="http://jekyllrb.com" target="_blank">Jekyll</a>
</p>
</footer>
<script type="text/javascript">
/* To avoid render blocking css */
var cb = function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.href = 'http://fonts.googleapis.com/css?family=Ubuntu+Mono&subset=latin';
var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);
</script>
<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- When no internet load JQuery from local -->
<script>window.jQuery || document.write('<script src="/assets/js/jquery.min.js"><\/script>')</script>
<!-- Site js -->
<script src="/assets/js/all.js"></script>
<!-- Google analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxx-x']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
cmake_minimum_required (VERSION 3.4)
cmake_minimum_required (VERSION 3.9)
set(CMAKE_BUILD_TYPE_INIT Release)
......@@ -13,13 +13,13 @@ project (pistache
include(GNUInstallDirs)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wconversion -pedantic -Wextra -Wno-missing-field-initializers")
add_compile_options(-Wall -Wconversion -pedantic -Wextra -Wno-missing-field-initializers)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${PROJECT_SOURCE_DIR}/CMakeModules)
include(CheckAtomic)
if(CMAKE_BUILD_TYPE MATCHES "Debug")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage -fstack-protector-all --param=ssp-buffer-size=4")
add_compile_options(-g -Og -ftest-coverage -fstack-protector-all --param=ssp-buffer-size=4)
endif()
option(BUILD_SHARED_LIBS "build shared library" ON)
......@@ -29,10 +29,15 @@ option(PISTACHE_BUILD_EXAMPLES "build examples alongside the project" OFF)
option(PISTACHE_BUILD_DOCS "build docs alongside the project" OFF)
option(PISTACHE_INSTALL "add pistache as install target (recommended)" ON)
option(PISTACHE_USE_SSL "add support for SSL server" OFF)
option(PISTACHE_PIC "Enable pistache PIC" ON)
# require fat LTO objects in static library
if(CMAKE_CXX_FLAGS MATCHES "-flto")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffat-lto-objects")
if(CMAKE_INTERPROCEDURAL_OPTIMIZATION OR CMAKE_CXX_FLAGS MATCHES "-flto" OR CMAKE_CXX_FLAGS MATCHES "-flto=thin")
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU")
add_compile_options(-ffat-lto-objects)
elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-flto=full)
endif()
endif()
if (PISTACHE_BUILD_TESTS)
......@@ -220,10 +225,9 @@ endif()
# Don't include these files in the archive...
set(CPACK_SOURCE_IGNORE_FILES
"/build/;/debian/;/prefix/;/.git*;~$;${CPACK_SOURCE_IGNORE_FILES}")
"/build/;/debian/;/prefix/;/.git*/;~$;${CPACK_SOURCE_IGNORE_FILES}")
# Include the CPack module for generating the archive and add the standard
# dist target to the generated makefile...
include(CPack)
add_custom_target(dist COMMAND ${CMAKE_MAKE_PROGRAM} package_source)
pistache.io
# Pistache
[![N|Solid](http://pistache.io/assets/images/logo.png)](https://www.github.com/oktal/pistache)
[![Travis Build Status](https://travis-ci.org/oktal/pistache.svg?branch=master)](https://travis-ci.org/oktal/pistache)
[![N|Solid](pistache.io/static/img/logo.png)](https://www.github.com/pistacheio/pistache)
[![Build Status](https://travis-ci.org/pistacheio/pistache.svg?branch=master)](https://travis-ci.org/pistacheio/pistache)
Pistache is a modern and elegant HTTP and REST framework for C++. It is entirely written in pure-C++14 and provides a clear and pleasant API.
......@@ -207,9 +206,9 @@ On Debian based distributions, `autopkgtest` implements the DEP-8 standard. To c
$ sudo apt install autopkgtest
```
Next create the test image, substituting `eoan` or `amd64` for other releases or architectures:
Next create the test image, substituting `groovy` or `amd64` for other releases or architectures:
```
$ autopkgtest-buildvm-ubuntu-cloud -r eoan -a amd64
$ autopkgtest-buildvm-ubuntu-cloud -r groovy -a amd64
```
Generate a Pistache source package in the parent directory of `pistache_source`:
......@@ -217,7 +216,7 @@ Generate a Pistache source package in the parent directory of `pistache_source`:
$ cd pistache_source
$ sudo apt build-dep pistache
$ ./debian/rules get-orig-source
$ debuild -S -sa
$ debuild -S -sa -uc
```
Test the source package on the host architecture in QEMU with KVM support and 8GB of RAM and four CPUs:
......
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="7px" height="7px" viewBox="0 0 7 7" enable-background="new 0 0 7 7" xml:space="preserve">
<rect fill="#666766" width="7" height="7"/>
</svg>
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 17.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="224px" height="64px" viewBox="0 0 224 64" enable-background="new 0 0 224 64" xml:space="preserve">
<path fill="#383838" d="M24,11c-0.6,0.3-1.2,0.4-1.9,0.5c0.7-0.4,1.2-1,1.4-1.8c-0.6,0.4-1.3,0.6-2.1,0.8c-0.6-0.6-1.5-1-2.4-1
c-1.8,0-3.3,1.5-3.3,3.3c0,0.3,0,0.5,0.1,0.7c-2.7-0.1-5.1-1.4-6.8-3.4c-0.3,0.5-0.4,1-0.4,1.7c0,1.1,0.6,2.1,1.5,2.7
c-0.5,0-1-0.2-1.5-0.4l0,0c0,1.6,1.1,2.9,2.6,3.2c-0.4,0.3-1,0.3-1.5,0c0.4,1.3,1.6,2.3,3.1,2.3c-1.1,0.9-2.5,1.4-4.1,1.4
c-0.3,0-0.5,0-0.8,0c1.5,0.9,3.2,1.5,5,1.5c6,0,9.3-5,9.3-9.3c0-0.1,0-0.3,0-0.4C23,12.3,23.6,11.7,24,11z"/>
<path fill="#383838" d="M78,16v8h3v-8h2l1-3h-3c0,0,0-0.5,0-1.3c0-0.3,0.2-0.7,0.7-0.7c1,0,2.9,0,2.3,0V8c0,0-1.6,0-3.3,0
C79,8,78,9.3,78,10.8s0,2.3,0,2.3h-2v3h2V16z"/>
<path fill="#383838" d="M112,24c-4.4,0-8-3.6-8-8s3.6-8,8-8s8,3.6,8,8S116.4,24,112,24z M118.7,17.1c-0.2-0.1-2.1-0.6-4.3-0.3
c0.9,2.5,1.1,3.7,1.3,4.9C117.4,20.6,118.4,19,118.7,17.1z M114.7,22.3c-0.2-1.2-0.5-2.7-1.5-5.2l0,0c-3.9,1.3-5.2,4-5.4,4.3
C109.4,22.7,112,23.2,114.7,22.3z M106.9,20.6c1.6-3.1,5.8-4.6,5.9-4.6c-0.2-0.4-0.4-0.8-0.6-1.2c-3.4,1-6.7,1-7,1
C105.1,17.7,105.8,19.4,106.9,20.6z M105.3,14.6c0.3,0,3.1,0,6.3-0.8c-1.1-2-2.3-3.7-2.5-4C107.2,10.7,105.8,12.5,105.3,14.6z
M110.4,9.4c0.2,0.3,1.4,1.9,2.5,4c2.4-0.9,3.5-2.3,3.6-2.5C115.3,9.8,113,8.9,110.4,9.4z M117.3,11.7c-0.1,0.2-1.3,1.7-3.8,2.7
c0.2,0.3,0.4,0.9,0.6,1.4c2.3-0.3,4,0,4.8,0.2C118.9,14.2,118.2,12.8,117.3,11.7z"/>
<path fill="#383838" d="M170,20c-1.1,0-2,0.9-2,2c0,1.1,0.9,2,2,2c1.1,0,2-0.9,2-2C172.1,21,171.1,20,170,20z M168,13.4v3.1
c4.2,0,7.5,3.6,7.5,7.5h3.1C178.6,18.2,173.8,13.4,168,13.4z M168,8v3.1c7.1,0,12.9,5.8,12.9,12.9h3.1C184,15.2,176.8,8,168,8z"/>
<path fill="#383838" d="M50.8,17.1c-0.6,0-1.1,0.7-1.1,1.6c0,0.9,0.5,1.6,1.1,1.6c0.6,0,1.1-0.7,1.1-1.6
C51.9,17.8,51.4,17.1,50.8,17.1z M54.7,13.1c0.1-0.3,0.1-2.1-0.6-3.8c0,0-1.6,0.2-4,1.8c-0.5-0.1-1.3-0.2-2.2-0.2s-1.7,0.1-2.2,0.2
c-2.4-1.6-4-1.8-4-1.8c-0.7,1.7-0.7,3.5-0.6,3.8C40.5,13.9,40,15,40,16.4c0,6.2,5.2,6.3,6.5,6.3c0.3,0,0.9,0,1.5,0
c0.6,0,1.2,0,1.5,0c1.3,0,6.5-0.1,6.5-6.3C56,15,55.5,13.9,54.7,13.1z M48,22L48,22c-3.3,0-5.9-0.4-5.9-3.6c0-0.8,0.3-1.5,0.9-2.1
c1.1-1,2.9-0.5,4.9-0.5c0,0,0,0,0,0c0,0,0,0,0,0c2.1,0,3.9-0.5,4.9,0.5c0.6,0.6,0.9,1.3,0.9,2.1C53.9,21.6,51.3,22,48,22z
M45.2,17.1c-0.6,0-1.1,0.7-1.1,1.6c0,0.9,0.5,1.6,1.1,1.6c0.6,0,1.1-0.7,1.1-1.6C46.4,17.8,45.9,17.1,45.2,17.1z"/>
<path fill="#383838" d="M143.1,11.8c-0.2-1.7-1.4-3-2.5-3s-2,1.3-1.8,2.9c0.2,1.7,1.4,3,2.5,3.1C142.4,14.8,143.2,13.4,143.1,11.8z
M141.2,18c-1.8,0-3.4,1.1-3.4,2.6s1.3,2.6,3,2.6c2.5,0,3.4-1.1,3.4-2.6c0-0.2,0-0.3-0.1-0.5c-0.2-0.8-0.9-1.2-1.8-1.9
C142,18.1,141.6,18,141.2,18z M143.2,8.8c1,0.4,1.5,1.6,1.5,2.9c0,1-0.6,1.9-1.3,2.6c-0.7,0.6-0.9,0.9-0.9,1.4
c0,0.5,0.8,1.2,1.2,1.5c1.2,1,1.6,1.8,1.6,3.2c0,1.8-1.6,3.6-4.5,3.6c-2.6,0-4.7-1.1-4.7-2.9c0-1.8,2-3.6,4.5-3.6h0.8
c-0.3-0.4-0.6-0.8-0.6-1.4c0-0.3,0.1-0.6,0.2-1c-0.2,0-0.3,0-0.4,0c-2.1,0-3.5-1.6-3.5-3.6c0-1.9,1.9-3.6,4-3.6h4.6l-1,0.8H143.2
L143.2,8.8z M151,12h-2v2h-1v-2h-2v-1h2V9h1v2h2V12z"/>
<path fill="#383838" d="M206.9,18.6c-0.4,2.2-0.9,4.3-2.5,5.4c-0.5-3.3,0.7-5.8,1.2-8.5c-0.9-1.5,0.1-4.6,2-3.9
c2.4,0.9-2.1,5.7,0.9,6.3c3.1,0.6,4.4-5.4,2.5-7.4c-2.8-2.8-8.1-0.1-7.5,4c0.2,1,1.2,1.3,0.4,2.7c-1.8-0.4-2.3-1.8-2.2-3.7
c0.1-3.1,2.8-5.2,5.4-5.5c3.4-0.4,6.5,1.2,7,4.4c0.5,3.6-1.5,7.4-5.1,7.2C208.1,19.5,207.7,19,206.9,18.6z"/>
<path fill="#FFFFFF" d="M24,43c-0.6,0.3-1.2,0.4-1.9,0.5c0.7-0.4,1.2-1,1.4-1.8c-0.6,0.4-1.3,0.6-2.1,0.8c-0.6-0.6-1.5-1-2.4-1
c-1.8,0-3.3,1.5-3.3,3.3c0,0.3,0,0.5,0.1,0.7c-2.7-0.1-5.1-1.4-6.8-3.4c-0.3,0.5-0.4,1-0.4,1.7c0,1.1,0.6,2.1,1.5,2.7
c-0.5,0-1-0.2-1.5-0.4l0,0c0,1.6,1.1,2.9,2.6,3.2c-0.4,0.3-1,0.3-1.5,0c0.4,1.3,1.6,2.3,3.1,2.3c-1.1,0.9-2.5,1.4-4.1,1.4
c-0.3,0-0.5,0-0.8,0c1.5,0.9,3.2,1.5,5,1.5c6,0,9.3-5,9.3-9.3c0-0.1,0-0.3,0-0.4C23,44.3,23.6,43.7,24,43z"/>
<path fill="#FFFFFF" d="M78,48v8h3v-8h2l1-3h-3c0,0,0-0.5,0-1.3c0-0.3,0.2-0.7,0.7-0.7c1,0,2.9,0,2.3,0v-3c0,0-1.6,0-3.3,0
C79,40,78,41.3,78,42.8s0,2.3,0,2.3h-2v3L78,48L78,48z"/>
<path fill="#FFFFFF" d="M112,56c-4.4,0-8-3.6-8-8s3.6-8,8-8s8,3.6,8,8S116.4,56,112,56z M118.7,49.1c-0.2-0.1-2.1-0.6-4.3-0.3
c0.9,2.5,1.1,3.7,1.3,4.9C117.4,52.6,118.4,51,118.7,49.1z M114.7,54.3c-0.2-1.2-0.5-2.7-1.5-5.2l0,0c-3.9,1.3-5.2,4-5.4,4.3
C109.4,54.7,112,55.2,114.7,54.3z M106.9,52.6c1.6-3.1,5.8-4.6,5.9-4.6c-0.2-0.4-0.4-0.8-0.6-1.2c-3.4,1-6.7,1-7,1
C105.1,49.7,105.8,51.4,106.9,52.6z M105.3,46.6c0.3,0,3.1,0,6.3-0.8c-1.1-2-2.3-3.7-2.5-4C107.2,42.7,105.8,44.5,105.3,46.6z
M110.4,41.4c0.2,0.3,1.4,1.9,2.5,4c2.4-0.9,3.5-2.3,3.6-2.5C115.3,41.8,113,40.9,110.4,41.4z M117.3,43.7c-0.1,0.2-1.3,1.7-3.8,2.7
c0.2,0.3,0.4,0.9,0.6,1.4c2.3-0.3,4,0,4.8,0.2C118.9,46.2,118.2,44.8,117.3,43.7z"/>
<path fill="#FFFFFF" d="M170,52c-1.1,0-2,0.9-2,2c0,1.1,0.9,2,2,2c1.1,0,2-0.9,2-2C172.1,53,171.1,52,170,52z M168,45.4v3.1
c4.2,0,7.5,3.6,7.5,7.5h3.1C178.6,50.2,173.8,45.4,168,45.4z M168,40v3.1c7.1,0,12.9,5.8,12.9,12.9h3.1C184,47.2,176.8,40,168,40z"
/>
<path fill="#FFFFFF" d="M50.8,49.1c-0.6,0-1.1,0.7-1.1,1.6c0,0.9,0.5,1.6,1.1,1.6c0.6,0,1.1-0.7,1.1-1.6
C51.9,49.8,51.4,49.1,50.8,49.1z M54.7,45.1c0.1-0.3,0.1-2.1-0.6-3.8c0,0-1.6,0.2-4,1.8c-0.5-0.1-1.3-0.2-2.2-0.2s-1.7,0.1-2.2,0.2
c-2.4-1.6-4-1.8-4-1.8c-0.7,1.7-0.7,3.5-0.6,3.8C40.5,45.9,40,47,40,48.4c0,6.2,5.2,6.3,6.5,6.3c0.3,0,0.9,0,1.5,0
c0.6,0,1.2,0,1.5,0c1.3,0,6.5-0.1,6.5-6.3C56,47,55.5,45.9,54.7,45.1z M48,54L48,54c-3.3,0-5.9-0.4-5.9-3.6c0-0.8,0.3-1.5,0.9-2.1
c1.1-1,2.9-0.5,4.9-0.5c0,0,0,0,0,0c0,0,0,0,0,0c2.1,0,3.9-0.5,4.9,0.5c0.6,0.6,0.9,1.3,0.9,2.1C53.9,53.6,51.3,54,48,54z
M45.2,49.1c-0.6,0-1.1,0.7-1.1,1.6c0,0.9,0.5,1.6,1.1,1.6c0.6,0,1.1-0.7,1.1-1.6C46.4,49.8,45.9,49.1,45.2,49.1z"/>
<path fill="#FFFFFF" d="M143.1,43.8c-0.2-1.7-1.4-3-2.5-3s-2,1.3-1.8,2.9c0.2,1.7,1.4,3,2.5,3.1C142.4,46.8,143.2,45.4,143.1,43.8z
M141.2,50c-1.8,0-3.4,1.1-3.4,2.6c0,1.4,1.3,2.6,3,2.6c2.5,0,3.4-1.1,3.4-2.6c0-0.2,0-0.3-0.1-0.5c-0.2-0.8-0.9-1.2-1.8-1.9
C142,50.1,141.6,50,141.2,50z M143.2,40.8c1,0.4,1.5,1.6,1.5,2.9c0,1-0.6,1.9-1.3,2.6c-0.7,0.6-0.9,0.9-0.9,1.4
c0,0.5,0.8,1.2,1.2,1.5c1.2,1,1.6,1.8,1.6,3.2c0,1.8-1.6,3.6-4.5,3.6c-2.6,0-4.7-1.1-4.7-2.9c0-1.8,2-3.6,4.5-3.6h0.8
c-0.3-0.4-0.6-0.8-0.6-1.4c0-0.3,0.1-0.6,0.2-1c-0.2,0-0.3,0-0.4,0c-2.1,0-3.5-1.6-3.5-3.6c0-1.9,1.9-3.6,4-3.6h4.6l-1,0.8H143.2
L143.2,40.8z M151,44h-2v2h-1v-2h-2v-1h2v-2h1v2h2V44z"/>
<path fill="#FFFFFF" d="M206.9,50.6c-0.4,2.2-0.9,4.3-2.5,5.4c-0.5-3.3,0.7-5.8,1.2-8.5c-0.9-1.5,0.1-4.6,2-3.9
c2.4,0.9-2.1,5.7,0.9,6.3c3.1,0.6,4.4-5.4,2.5-7.4c-2.8-2.8-8.1-0.1-7.5,4c0.2,1,1.2,1.3,0.4,2.7c-1.8-0.4-2.3-1.8-2.2-3.7
c0.1-3.1,2.8-5.2,5.4-5.5c3.4-0.4,6.5,1.2,7,4.4c0.5,3.6-1.5,7.4-5.1,7.2C208.1,51.5,207.7,51,206.9,50.6z"/>
</svg>
This diff is collapsed.
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, main {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
\ No newline at end of file
.highlight { background: #ffffff; }
.highlight .c { color: #999988; font-style: italic } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { font-weight: bold } /* Keyword */
.highlight .o { font-weight: bold } /* Operator */
.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #999999; font-weight: bold } /* Comment.Preproc */
.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */
.highlight .cs { color: #999999; font-weight: bold; font-style: italic } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .gd .x { color: #000000; background-color: #ffaaaa } /* Generic.Deleted.Specific */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #999999 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .gi .x { color: #000000; background-color: #aaffaa } /* Generic.Inserted.Specific */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #aaaaaa } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { font-weight: bold } /* Keyword.Constant */
.highlight .kd { font-weight: bold } /* Keyword.Declaration */
.highlight .kp { font-weight: bold } /* Keyword.Pseudo */
.highlight .kr { font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #445588; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #009999 } /* Literal.Number */
.highlight .s { color: #d14 } /* Literal.String */
.highlight .na { color: #008080 } /* Name.Attribute */
.highlight .nb { color: #0086B3 } /* Name.Builtin */
.highlight .nc { color: #445588; font-weight: bold } /* Name.Class */
.highlight .no { color: #008080 } /* Name.Constant */
.highlight .ni { color: #800080 } /* Name.Entity */
.highlight .ne { color: #990000; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #990000; font-weight: bold } /* Name.Function */
.highlight .nn { color: #555555 } /* Name.Namespace */
.highlight .nt { color: #000080 } /* Name.Tag */
.highlight .nv { color: #008080 } /* Name.Variable */
.highlight .ow { font-weight: bold } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mf { color: #009999 } /* Literal.Number.Float */
.highlight .mh { color: #009999 } /* Literal.Number.Hex */
.highlight .mi { color: #009999 } /* Literal.Number.Integer */
.highlight .mo { color: #009999 } /* Literal.Number.Oct */
.highlight .sb { color: #d14 } /* Literal.String.Backtick */
.highlight .sc { color: #d14 } /* Literal.String.Char */
.highlight .sd { color: #d14 } /* Literal.String.Doc */
.highlight .s2 { color: #d14 } /* Literal.String.Double */
.highlight .se { color: #d14 } /* Literal.String.Escape */
.highlight .sh { color: #d14 } /* Literal.String.Heredoc */
.highlight .si { color: #d14 } /* Literal.String.Interpol */
.highlight .sx { color: #d14 } /* Literal.String.Other */
.highlight .sr { color: #009926 } /* Literal.String.Regex */
.highlight .s1 { color: #d14 } /* Literal.String.Single */
.highlight .ss { color: #990073 } /* Literal.String.Symbol */
.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */
.highlight .vc { color: #008080 } /* Name.Variable.Class */
.highlight .vg { color: #008080 } /* Name.Variable.Global */
.highlight .vi { color: #008080 } /* Name.Variable.Instance */
.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */
jQuery(document).ready(function($){
// todo: jquery stuff should need to put here.
});
This diff is collapsed.
/* Modernizr 2.8.3 (Custom Build) | MIT & BSD
* Build: http://modernizr.com/download/#-borderradius-shiv-cssclasses-teststyles-testprop-testallprops-prefixes-domprefixes-load
*/
;window.Modernizr=function(a,b,c){function z(a){j.cssText=a}function A(a,b){return z(m.join(a+";")+(b||""))}function B(a,b){return typeof a===b}function C(a,b){return!!~(""+a).indexOf(b)}function D(a,b){for(var d in a){var e=a[d];if(!C(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function E(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:B(f,"function")?f.bind(d||b):f}return!1}function F(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+o.join(d+" ")+d).split(" ");return B(b,"string")||B(b,"undefined")?D(e,b):(e=(a+" "+p.join(d+" ")+d).split(" "),E(e,b,c))}var d="2.8.3",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n="Webkit Moz O ms",o=n.split(" "),p=n.toLowerCase().split(" "),q={},r={},s={},t=[],u=t.slice,v,w=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["&#173;",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},x={}.hasOwnProperty,y;!B(x,"undefined")&&!B(x.call,"undefined")?y=function(a,b){return x.call(a,b)}:y=function(a,b){return b in a&&B(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=u.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(u.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(u.call(arguments)))};return e}),q.borderradius=function(){return F("borderRadius")};for(var G in q)y(q,G)&&(v=G.toLowerCase(),e[v]=q[G](),t.push((e[v]?"":"no-")+v));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)y(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},z(""),i=k=null,function(a,b){function l(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function m(){var a=s.elements;return typeof a=="string"?a.split(" "):a}function n(a){var b=j[a[h]];return b||(b={},i++,a[h]=i,j[i]=b),b}function o(a,c,d){c||(c=b);if(k)return c.createElement(a);d||(d=n(c));var g;return d.cache[a]?g=d.cache[a].cloneNode():f.test(a)?g=(d.cache[a]=d.createElem(a)).cloneNode():g=d.createElem(a),g.canHaveChildren&&!e.test(a)&&!g.tagUrn?d.frag.appendChild(g):g}function p(a,c){a||(a=b);if(k)return a.createDocumentFragment();c=c||n(a);var d=c.frag.cloneNode(),e=0,f=m(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function q(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return s.shivMethods?o(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/[\w\-]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(s,b.frag)}function r(a){a||(a=b);var c=n(a);return s.shivCSS&&!g&&!c.hasCSS&&(c.hasCSS=!!l(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),k||q(a,c),a}var c="3.7.0",d=a.html5||{},e=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,f=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,g,h="_html5shiv",i=0,j={},k;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",g="hidden"in a,k=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){g=!0,k=!0}})();var s={elements:d.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:c,shivCSS:d.shivCSS!==!1,supportsUnknownElements:k,shivMethods:d.shivMethods!==!1,type:"default",shivDocument:r,createElement:o,createDocumentFragment:p};a.html5=s,r(b)}(this,b),e._version=d,e._prefixes=m,e._domPrefixes=p,e._cssomPrefixes=o,e.testProp=function(a){return D([a])},e.testAllProps=F,e.testStyles=w,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+t.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
\ No newline at end of file
pistache (0.0.002-pistache1) focal; urgency=medium
pistache (0.0.002-pistache1) groovy; urgency=medium
* Latest upstream.
-- Kip Warner <kip@thevertigo.com> Sun, 02 Aug 2020 18:26:47 -0700
-- Kip Warner <kip@thevertigo.com> Sun, 27 Dec 2020 16:40:00 -0700
......@@ -17,9 +17,9 @@ Build-Depends:
pkg-config (>= 0.28),
rapidjson-dev (>= 1.1.0),
valgrind
Vcs-Git: https://github.com/oktal/pistache.git
Vcs-browser: https://www.github.com/oktal/pistache
Homepage: https://www.github.com/oktal/pistache
Vcs-Git: https://github.com/pistacheio/pistache.git
Vcs-browser: https://github.com/pistacheio/pistache
Homepage: https://github.com/pistacheio/pistache
Package: libpistache-dev
Architecture: any
......@@ -31,7 +31,7 @@ Depends:
libssl-dev
Description: elegant C++ REST framework
Pistache is a C++ REST framework originally written by Mathieu Stefani at
Datacratic, since maintained by other volunteers. It is written in pure C++11
Datacratic, since maintained by other volunteers. It is written in pure C++14
with no external dependency and provides a low-level HTTP abstraction.
.
Pistache provides both an HTTP client and server that can be used to create and
......@@ -50,7 +50,7 @@ Depends:
${shlibs:Depends}
Description: elegant C++ REST framework
Pistache is a C++ REST framework originally written by Mathieu Stefani at
Datacratic, since maintained by other volunteers. It is written in pure C++11
Datacratic, since maintained by other volunteers. It is written in pure C++14
with no external dependency and provides a low-level HTTP abstraction.
.
Pistache provides both an HTTP client and server that can be used to create and
......
This diff is collapsed.
......@@ -85,7 +85,8 @@ public:
Version version() const;
Code code() const;
std::string body() const;
const std::string &body() const;
std::string body();
const CookieJar &cookies() const;
CookieJar &cookies();
......@@ -213,7 +214,7 @@ public:
friend class ResponseWriter;
explicit Timeout(Timeout &&other)
: handler(other.handler), request(std::move(other.request)),
: handler(other.handler),
transport(other.transport), armed(other.armed), timerFd(other.timerFd),
peer(std::move(other.peer)) {
// cppcheck-suppress useInitializationList
......@@ -223,7 +224,7 @@ public:
Timeout &operator=(Timeout &&other) {
handler = other.handler;
transport = other.transport;
request = std::move(other.request);
version = other.version;
armed = other.armed;
timerFd = other.timerFd;
other.timerFd = -1;
......@@ -257,13 +258,13 @@ public:
private:
Timeout(const Timeout &other) = default;
Timeout(Tcp::Transport *transport_, Handler *handler_, Request request_,
Timeout(Tcp::Transport *transport_, Http::Version version, Handler *handler_,
std::weak_ptr<Tcp::Peer> peer_);
void onTimeout(uint64_t numWakeup);
Handler *handler;
Request request;
Http::Version version;
Tcp::Transport *transport;
bool armed;
Fd timerFd;
......@@ -355,9 +356,8 @@ public:
friend class Private::ResponseLineStep;
ResponseWriter(Tcp::Transport *transport, Request request, Handler *handler,
std::weak_ptr<Tcp::Peer> peer);
ResponseWriter(Http::Version version, Tcp::Transport *transport,
Handler *handler, std::weak_ptr<Tcp::Peer> peer);
//
// C++11: std::weak_ptr move constructor is C++14 only so the default
......@@ -421,6 +421,12 @@ public:
ResponseWriter clone() const;
std::shared_ptr<Tcp::Peer> getPeer() const {
if (auto sp = peer_.lock())
return sp;
return nullptr;
}
private:
ResponseWriter(const ResponseWriter &other);
......@@ -433,9 +439,9 @@ private:
Response response_;
std::weak_ptr<Tcp::Peer> peer_;
DynamicStreamBuf buf_;
Tcp::Transport *transport_;
Tcp::Transport *transport_ = nullptr;
Timeout timeout_;
ssize_t sent_bytes_;
ssize_t sent_bytes_ = 0;
};
Async::Promise<ssize_t>
......@@ -592,6 +598,8 @@ using ResponseParser = Private::ParserImpl<Http::Response>;
class Handler : public Tcp::Handler {
public:
static constexpr const char* ParserData = "__Parser";
virtual void onRequest(const Request &request, ResponseWriter response) = 0;
virtual void onTimeout(const Request &request, ResponseWriter response);
......@@ -623,13 +631,12 @@ public:
return bodyTimeout_;
}
static RequestParser &getParser(const std::shared_ptr<Tcp::Peer> &peer);
static std::shared_ptr<RequestParser> getParser(const std::shared_ptr<Tcp::Peer> &peer);
virtual ~Handler() override {}
private:
void onConnection(const std::shared_ptr<Tcp::Peer> &peer) override;
void onDisconnection(const std::shared_ptr<Tcp::Peer> &peer) override;
void onInput(const char *buffer, size_t len,
const std::shared_ptr<Tcp::Peer> &peer) override;
private:
......
......@@ -86,7 +86,6 @@ struct Event {
explicit Event(Tag _tag);
Flags<NotifyOn> flags;
Fd fd;
Tag tag;
};
......
......@@ -9,7 +9,6 @@
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <pistache/async.h>
#include <pistache/http.h>
......@@ -31,6 +30,8 @@ class Transport;
class Peer {
public:
friend class Transport;
friend class Http::Handler;
friend class Http::Timeout;
~Peer();
......@@ -48,6 +49,7 @@ public:
std::shared_ptr<void> tryGetData(std::string name) const;
Async::Promise<ssize_t> send(const RawBuffer &buffer, int flags = 0);
size_t getID() const;
protected:
Peer(Fd fd, const Address &addr, void *ssl);
......@@ -64,6 +66,7 @@ private:
std::unordered_map<std::string, std::shared_ptr<void>> data_;
void *ssl_ = nullptr;
const size_t id_;
};
std::ostream &operator<<(std::ostream &os, Peer &peer);
......
......@@ -43,7 +43,6 @@ public:
bool isWritable() const { return flags.hasFlag(Polling::NotifyOn::Write); }
bool isHangup() const { return flags.hasFlag(Polling::NotifyOn::Hangup); }
Fd getFd() const { return this->fd; }
Polling::Tag getTag() const { return this->tag; }
};
......@@ -120,7 +119,7 @@ public:
void modifyFd(const Key &key, Fd fd, Polling::NotifyOn interest,
Polling::Tag tag, Polling::Mode mode = Polling::Mode::Level);
void removeFd(const Key& key, Fd fd);
void removeFd(const Key &key, Fd fd);
void runOnce();
void run();
......
......@@ -67,6 +67,9 @@ struct Route {
typedef std::function<bool(Http::Request& req, Http::ResponseWriter& resp)> Middleware;
typedef std::function<void(const std::shared_ptr<Tcp::Peer> &peer)>
DisconnectHandler;
explicit Route(Route::Handler handler) : handler_(std::move(handler)) {}
template <typename... Args> void invokeHandler(Args &&... args) const {
......@@ -223,10 +226,13 @@ public:
void addMiddleware(Route::Middleware middleware);
void addNotFoundHandler(Route::Handler handler);
void addDisconnectHandler(Route::DisconnectHandler handler);
inline bool hasNotFoundHandler() { return notFoundHandler != nullptr; }
void invokeNotFoundHandler(const Http::Request &req,
Http::ResponseWriter resp) const;
void disconnectPeer(const std::shared_ptr<Tcp::Peer> &peer);
Route::Status route(const Http::Request &request,
Http::ResponseWriter response);
......@@ -239,6 +245,8 @@ private:
std::vector<Route::Middleware> middlewares;
std::vector<Route::DisconnectHandler> disconnectHandlers;
Route::Handler notFoundHandler;
};
......@@ -266,6 +274,8 @@ public:
void onRequest(const Http::Request &req,
Http::ResponseWriter response) override;
void onDisconnection(const std::shared_ptr<Tcp::Peer> &peer) override;
private:
std::shared_ptr<Rest::Router> router;
};
......@@ -282,7 +292,7 @@ public:
std::vector<TypedParam> splat() const;
private:
explicit Request(const Http::Request &request,
explicit Request(Http::Request request,
std::vector<TypedParam> &&params,
std::vector<TypedParam> &&splats);
......
......@@ -27,6 +27,7 @@ enum class Options : uint64_t {
QuickAck = FastOpen << 1,
ReuseAddr = QuickAck << 1,
ReusePort = ReuseAddr << 1,
CloseOnExec = ReusePort << 1,
};
DECLARE_FLAGS_OPERATORS(Options)
......
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Pistache</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Pistache is a C++ REST framework focussed on high performance and clear API. Pistache is a free software written by Mathieu Stefani and available on Github - https://github.com/oktal/pistache
">
<link rel="canonical"
href="http://pistache.io/">
<!-- Harmony styles -->
<link rel="stylesheet" type="text/css" href="/assets/css/main.css">
<!-- Modernizr js -->
<script async src="/assets/js/modernizr.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.min.css" />
<!--[if lt IE 9]>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.ie.min.css" />
<![endif]-->
<!-- IE Fixes -->
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="theme-base-01">
<header class="main-header">
<div class="wc-container">
<img id="img-logo" src="/assets/images/logo.png" />
<h1>
<a href="/">Pistache</a>
</h1>
<h2>An elegant C++ REST framework.</h2>
<ul>
<li>
<a class="active" href="/" class="active">Pistache</a><span>/</span>
</li>
<li>
<a href="/quickstart">Getting Started</a><span>/</span>
</li>
<li>
<a href="/guide/">User's Guide</a><span>/</span>
</li>
<li>
<a title="Pistache on Github"
href="https://github.com/oktal/pistache" target="_blank">
Source code
</a><span>/</span>
</li>
</ul>
<div style="text-align: center">
<iframe src="https://ghbtns.com/github-btn.html?user=oktal&repo=pistache&type=star&count=true&size=large" frameborder="0" scrolling="0" width="160px" height="30px"></iframe>
<iframe src="https://ghbtns.com/github-btn.html?user=oktal&repo=pistache&type=fork&count=true&size=large" frameborder="0" scrolling="0" width="158px" height="30px"></iframe>
</div>
</div>
</header>
<div class="page-content wc-container">
<div class="post">
<h1>Pistache</h1>
<div class="post">
<p><code>Pistache</code> is a C++ REST framework written by <a href="https://github.com/oktal">Mathieu Stefani</a> at <a href="http://datacratic.com">Datacratic</a>.
It is written in pure C++14 and provides a low-level HTTP abstraction.</p>
<p><code>Pistache</code> provides both an HTTP client and server that can be used to create and query complex web and REST APIs.</p>
<p>It’s completly free and Apache-licensed.</p>
<h2 id="modern-api">Modern API</h2>
<p>Playing with Pistache and its modern API is fun and easy</p>
<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">struct</span> <span class="nl">HelloHandler</span> <span class="p">:</span> <span class="k">public</span> <span class="n">Http</span><span class="o">::</span><span class="n">Handler</span> <span class="p">{</span>
<span class="kt">void</span> <span class="n">onRequest</span><span class="p">(</span><span class="k">const</span> <span class="n">Http</span><span class="o">::</span><span class="n">Request</span><span class="o">&amp;</span> <span class="n">req</span><span class="p">,</span> <span class="n">Http</span><span class="o">::</span><span class="n">ResponseWriter</span> <span class="n">response</span><span class="p">)</span> <span class="p">{</span>
<span class="n">response</span><span class="p">.</span><span class="n">send</span><span class="p">(</span><span class="n">Http</span><span class="o">::</span><span class="n">Code</span><span class="o">::</span><span class="n">Ok</span><span class="p">,</span> <span class="s">&quot;Hello, World&quot;</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">};</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
<span class="n">Http</span><span class="o">::</span><span class="n">listenAndServe</span><span class="o">&lt;</span><span class="n">HelloHandler</span><span class="o">&gt;</span><span class="p">(</span><span class="s">&quot;*:9080&quot;</span><span class="p">);</span>
<span class="p">}</span></code></pre></figure>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash">curl http://127.0.0.1:9080
Hello, World</code></pre></figure>
<h2 id="whats-in-the-box">What’s in the box</h2>
<ul>
<li>A multi-threaded http server to build your APIs</li>
<li>An asynchronous http client to request APIS</li>
<li>An HTTP router to dispatch requests to C++ functions</li>
<li>A REST description DSL to easily define your APIs</li>
<li>Type-safe headers and MIME types implementation</li>
</ul>
<h2 id="use-it">Use it</h2>
<ul>
<li>Clone it on <a href="http://github.com/oktal/pistache">github</a></li>
<li>Start with the <a href="quickstart">quickstart</a></li>
<li>Read the full user’s <a href="guide">guide</a></li>
<li>Have issues with it ? Fill an <a href="https://github.com/oktal/pistache/issues">issue</a></li>
</ul>
</div>
</div>
</div>
<footer class="main-footer">
<div class="wc-container">
<div class="column one">
<h6>Few more links</h6>
<ul class="menu">
</ul>
</div>
<div class="column two">
<h6>Follow me</h6>
<ul class="social-media">
<li>
<a title="oktal on Github"
href="https://github.com/oktal"
class="github wc-img-replace" target="_blank">Github</a>
</li>
</ul>
</div>
</div>
<p class="wc-container disclaimer">
Powered by <a href="http://jekyllrb.com" target="_blank">Jekyll</a>
</p>
</footer>
<script type="text/javascript">
/* To avoid render blocking css */
var cb = function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.href = 'http://fonts.googleapis.com/css?family=Ubuntu+Mono&subset=latin';
var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);
</script>
<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- When no internet load JQuery from local -->
<script>window.jQuery || document.write('<script src="/assets/js/jquery.min.js"><\/script>')</script>
<!-- Site js -->
<script src="/assets/js/all.js"></script>
<!-- Google analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxx-x']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
# Dependencies
/node_modules
# Production
/build
# Generated files
.docusaurus
.cache-loader
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Website
This website is built using [Docusaurus 2](https://v2.docusaurus.io/), a modern static website generator.
## Installation
```console
yarn install
```
## Local Development
```console
yarn start
```
This command starts a local development server and open up a browser window. Most changes are reflected live without having to restart the server.
## Build
```console
yarn build
```
This command generates static content into the `build` directory and can be served using any static contents hosting service.
## Deployment
```console
GIT_USER=<Your GitHub username> USE_SSH=true yarn deploy
```
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
module.exports = {
presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
};
---
title: Asynchronous HTTP programming
---
Interfaces provided by Pistaches are _asynchronous_ and _non-blocking_. Asynchronous programming allows for code to continue executing even if the result of a given call is not available yet. Calls that provide an asynchronous interface are referred to _asynchronous calls_.
An example of such a call is the `send()` function provided by the `ResponseWriter` interface. This function returns the number of bytes written to the socket file descriptor associated to the connection. However, instead of returning directly the value to the caller and thus blocking the caller, it wraps the value into a component called a `Promise`.
A `Promise` is the Pistache’s implementation of the [Promises/A+](https://promisesaplus.com) standard available in many JavaScript implementations. Simply put, during an asynchronous call, a `Promise` separates the launch of an asynchronous operation from the retrieval of its result. While the asynchronous might still be running, a `Promise<T>` is directly returned to the caller to retrieve the final result when it becomes available. A so called continuation can be attach to a `Promise` to execute a callback when the result becomes available (when the `Promise` has been resolved or fulfilled).
```cpp
auto res = response.send(Http::Code::Ok, "Hello World");
res.then(
[](ssize_t bytes) { std::cout << bytes << " bytes have been sent\n" },
Async::NoExcept
);
```
The `then()` member is used to attach a callback to the `Promise`. The first argument is a callable that will be called when the `Promise` has been **succesfully** resolved. If, for some reason, an error occurs during the asynchronous operation, a `Promise` can be **rejected** and will then fail. In this case, the second callable will be called. `Async::NoExcept` is a special callback that will call [`std::terminate()`](https://en.cppreference.com/w/cpp/error/terminate) if the promise failed. This is the equivalent of the `noexcept` keyword.
Other generic callbacks can also be used in this case:
- `Async::IgnoreException` will simply ignore the exception and let the program continue
- `Async::Throw` will "rethrow" the exception up to an eventual promise call-chain. This has the same effect than the `throw` keyword, except that it is suitable for promises
Exceptions in promises callbacks are propagated through an `exception_ptr`. Promises can also be chained together to create a whole asynchronous pipeline:
```cpp
auto fetchOp = fetchDatabase();
fetchOp
.then(
[](const User& user) { return fetchUserInfo(user); },
Async::Throw)
.then(
[](const UserInfo& info) { std::cout << "User name = " << info.name << std::endl; },
[](exception_ptr ptr) { std::cout << "An exception occured during user retrieval" << std::endl;}
);
```
Line 5 will propagate the exception if `fetchDatabase()` failed and rejected the promise.
---
title: Headers
---
## Overview
Inspired by the [Rust](https://www.rust-lang.org) eco-system and [Hyper](https://hyper.rs), HTTP headers are represented as _type-safe_ plain objects. Instead of representing headers as a pair of `(key: string, value: value)`, the choice has been made to represent them as plain objects. This greatly reduces the risk of typo errors that can not catched by the compiler with plain old strings.
Instead, objects give the compiler the ability to catch errors directly at compile-time, as the user can not add or request a header through its name: it has to use the whole **type**. Types being enforced at compile-time, it helps reducing common typo errors.
With Pistache, each HTTP Header is a class that inherits from the `Http::Header` base class and use the `NAME()` macro to define the name of the header. List of all headers inside an HTTP request or response are stored inside an internal [`std::unordered_map`](https://en.cppreference.com/w/cpp/container/unordered_map), wrapped in an `Header::Collection` class. Invidual headers can be retrieved or added to this object through the whole type of the header:
```cpp
auto headers = request.headers();
auto ct = headers.get<Http::Header::ContentType>();
```
`get<H>` will return a `std::shared_ptr<H>` where `H: Header` (`H` inherits from `Header`). If the header does not exist, `get<H>` will throw an exception. `tryGet<H>` provides a non-throwing alternative that, instead, returns a null pointer.
:::note Built-in headers
Headers provided by Pistache live in the `Http::Header` namespace
:::
## Defining your own header
Common headers defined by the HTTP RFC ([RFC2616](https://pretty-rfc.herokuapp.com/RFC2616)) are already implemented and available. However, some APIs might define extra headers that do not exist in Pistache. To support your own header types, you can define and register your own HTTP Header by first declaring a class that inherits the `Http::Header` class:
```cpp
class XProtocolVersion : public Http::Header {
};
```
Since every header has a name, the `NAME()` macro must be used to name the header properly:
```cpp
class XProtocolVersion : public Http::Header {
NAME("X-Protocol-Version")
};
```
The `Http::Header` base class provides two virtual methods that you must override in your own implementation:
```cpp
void parse(const std::string& data);
```
This function is used to parse the header from the string representation. Alternatively, to avoid allocating memory for the string representation, a _raw_ version can be used:
```cpp
void parseRaw(const char* str, size_t len);
```
`str` will directly point to the header buffer from the raw http stream. The len parameter is the total length of the header's value.
```cpp
void write(std::ostream& stream) const
```
When writing the response back to the client, the `write` function is used to serialize the header into the network buffer.
Let’s combine these functions together to finalize the implementation of our previously declared header:
```cpp
class XProtocolVersion : public Http::Header {
public:
NAME("X-Protocol-Version")
XProtocolVersion()
: minor(-1)
, major(-1)
{ }
void parse(const std::string& data) {
auto pos = data.find('.');
if (pos != std::string::npos) {
minor = std::stoi(data.substr(0, pos));
major = std::stoi(data.substr(pos + 1));
}
}
void write(std::ostream& os) const {
os << minor << "." << major;
}
private:
int minor;
int major;
};
```
And that’s it. Now all we have to do is registering the header to the registry system:
```cpp
Header::Registry::registerHeader<XProtocolVersion>();
```
:::note Header instantation
You should always provide a default constructor for your header so that it can be instantiated by the registry system
:::
Now, the `XProtocolVersion` can be retrieved and added like any other header in the `Header::Collection` class.
:::note Unknown headers
Headers that are not known to the registry system are stored as a raw pair of strings in the `Collection` class. `getRaw()` can be used to retrieve a raw header:
```cpp
auto myHeader = request.headers().getRaw("x-raw-header");
myHeader.name() // x-raw-header
myHeader.value() // returns the value of the header as a string
```
:::
## MIME types
[MIME Types](https://en.wikipedia.org/wiki/Media_type) (or Media Type) are also fully typed. Such types are for example used in an HTTP request or response to describe the data contained in the body of the message (`Content-Type` header, …) and are composed of a _type_, _subtype_, and optional _suffix_ and parameters.
MIME Types are represented by the `Mime::MediaType` class, implemented in the `mime.h` header. A MIME type can be directly constructed from a string:
```cpp
auto mime = Http::Mime::MediaType::fromString("application/json");
```
However, to enforce type-safety, common types are all represented as enumerations:
```cpp
Http::Mime::MediaType m1(Http::Mime::Type::Application, Http::Mime::Subtype::Json);
```
To avoid such a typing pain, a `MIME` macro is also provided:
```cpp
auto m1 = MIME(Application, Json);
```
For suffix MIMEs, use the special `MIME3` macro:
```cpp
auto m1 = MIME3(Application, Json, Zip);
```
If you like typing, you can also use the long form:
```cpp
Http::Mime::MediaType m1(Http::Mime::Type::Application, Http::Mime::Subtype::Json, Http::Mime::Suffix::Zip);
```
The `toString()` function can be used to get the string representation of a given MIME type:
```cpp
auto m1 = MIME(Text, Html);
m1.toString(); // text/html
```
---
id: http-handler
title: HTTP handler
---
Requests that are received by Pistache are handled by a special class called `Http::Handler`. This class declares a bunch of virtual methods that can be overriden to handle special events that occur on the socket and/or connection.
The `onRequest()` function must be overriden. This function is called whenever Pistache received data and correctly parsed it as an HTTP request.
```cpp
virtual void onRequest(const Http::Request& request, Http::ResponseWriter response);
```
The first argument is an object of type `Http::Request` representing the request itself. It contains a bunch of informations including:
- The resource associated to the request
- The query parameters
- The headers
- The body of the request
The `Request` object gives a read-only access to these informations. You can access them through a couple of getters but can not modify them. An HTTP request is **immutable**.
## Sending a response
`ResponseWriter` is an object from which the final HTTP response is sent to the client. The `onRequest()` function does not return anything (`void`). Instead, the response is sent through the `ResponseWriter` class. This class provides a bunch of `send()` function overloads to send the response:
```cpp
Async::Promise<ssize_t> send(Code code);
```
You can use this overload to send a response with an empty body and a given HTTP Code (e.g `Http::Code::Ok`)
```cpp
Async::Promise<ssize_t> send(
Code code,
const std::string& body,
const Mime::MediaType &mime = Mime::MediaType()
);
```
This overload can be used to send a response with static, fixed-size content (body). A MIME type can also be specified, which will be sent through the `Content-Type` header.
```cpp
template<size_t N>
Async::Promise<ssize_t> send(
Code code,
const char (&arr)[N],
const Mime::MediaType& mime = Mime::MediaType()
);
```
This version can also be used to send a fixed-size response with a body except that it does not need to construct a string (no memory is allocated). The size of the content is directly deduced by the compiler. This version only works with raw string literals.
These functions are asynchronous, meaning that they do not return a plain old `ssize_t` value indicating the number of bytes being sent, but instead a `Promise` that will be fulfilled later on. See the next section for more details on asynchronous programming with Pistache.
## Response streaming
Sometimes, content that is to be sent back to the user can not be known in advance, thus the length can not be determined in advance. For that matter, the HTTP specification defines a special data-transfer mechanism called [chunked encoding](https://tools.ietf.org/html/rfc7230#section-4.1) where data is sent in a series of _chunks_. This mechanism uses the `Transfer-Encoding` HTTP header in place of the `Content-Length` one.
To stream content, Pistache provides a special `ResponseStream` class. To get a `ResponseStream` from a `ResponseWriter`, call the `stream()` member function:
```cpp
auto stream = response.stream(Http::Code::Ok);
```
To initate a stream, you have to pass the HTTP status code to the stream function (here `Http::Code::Ok` or `HTTP 200`). The `ResponseStream` class provides an `iostream` like interface that overloads the `<<` operator.
```cpp
stream << "PO"
stream << "NG"
```
The first line will write a chunk of size 2 with the content _PO_ to the stream's buffer. The second line will write a second chunk of size 2 with the content _NG_. To end the stream and flush the content, use the special `ends` marker:
```cpp
stream << ends
```
The `ends` marker will write the last chunk of size 0 and send the final data over the network. To simply flush the stream's buffer without ending the stream, you can use the `flush` marker:
```cpp
stream << flush
```
:::caution Headers writing
After starting a stream, headers become immutable. They must be written to the response before creating a `ResponseStream`:
```cpp
response.headers()
.add<Header::Server>("lys")
.add<Header::ContentType>(MIME(Text, Plain));
auto stream = response.stream();
stream << "PO" << "NG" << ends;
```
:::
## Static file serving
In addition to text content serving, Pistache provides a way to serve static files through the `Http::serveFile` function:
```cpp
if (request.resource() == "/doc" && request.method == Http::Method::Get) {
Http::serveFile(response, "README.md");
}
```
:::note Return value
`serveFile` also returns a `Promise` representing the total number of bytes being sent to the wire
:::
## Controlling timeout
Sometimes, you might require to timeout after a certain amount of time. For example, if you are designing an HTTP API with soft real-time constraints, you will have a time constraint to send a response back to the client. That is why Pistache provides the ability to control the timeout on a per-request basis. To arm a timeout on a response, you can use the `timeoufterAfter()` member function directly on the `ResponseWriter` object:
```cpp
response.timeoutAfter(std::chrono::milliseconds(500));
```
This will trigger a timeout if a response has not been sent within 500 milliseconds. `timeoutAfter` accepts any kind of duration.
When a timeout triggers, the `onTimeout()` function from your handler will be called. By default, this method does nothing. If you want to handle your timeout properly, you should then override this function inside your own handler:
```cpp
void onTimeout(const Http::Request& request, Http::ResponseWriter writer) {
request.send(Http::Code::No_Content);
}
```
The `Request` object that is passed to the `onTimeout` is the exact same request that triggered the timeout. The `ResponseWriter` is a complete new writer object.
:::note ResponseWriter state
Since the `ResponseWriter` object is a complete new object, state is not preserved with the `ResponseWriter` from the `onRequest()` callback, which means that you will have to write the complete response again, including headers and cookies.
:::
---
title: Getting started
slug: /
---
Pistache is a web framework written in Modern C++ that focuses on performance and provides an elegant and asynchronous API.
```cpp
#include <pistache/pistache.h>
```
## Installing Pistache
[git](https://git-scm.com) is needed to retrieve the sources. Compiling the sources will require [CMake](https://cmake.org) to generate build files and a recent compiler that supports C++17.
If you're on Ubuntu and want to skip the compilation process you can add the official PPA providing nightly builds:
```shell
sudo add-apt-repository ppa:pistache+team/unstable
sudo apt update
sudo apt install libpistache-dev
```
Otherwise, here's how to build and install the latest release:
```shell
git clone --recurse-submodules https://github.com/pistacheio/pistache.git
cd pistache
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make
sudo make install
```
Also, Pistache does not support Windows yet, but should work fine under [WSL](https://docs.microsoft.com/windows/wsl/about).
## Serving requests
### Include
First, let’s start by including the right header.
```cpp
#include <pistache/endpoint.h>
```
### Hello world
Requests received by Pistache are handled with an `Http::Handler`.
Let’s start by defining a simple `HelloHandler`:
```cpp
using namespace Pistache;
class HelloHandler : public Http::Handler {
public:
HTTP_PROTOTYPE(HelloHandler)
void onRequest(const Http::Request& request, Http::ResponseWriter response) {
response.send(Http::Code::Ok, "Hello, World\n");
}
};
```
Handlers must inherit the `Http::Handler` class and at least define the `onRequest` member function. They must also define a `clone()` member function. Simple handlers can use the special `HTTP_PROTOTYPE` macro, passing in the name of the class. The macro will take care of defining the `clone()` member function for you.
### Final touch
After defining the handler, the server can now be started:
```cpp
int main() {
Address addr(Ipv4::any(), Port(9080));
auto opts = Http::Endpoint::options().threads(1);
Http::Endpoint server(addr);
server.init(opts);
server.setHandler(Http::make_handler<HelloHandler>());
server.serve();
}
```
For simplicity, you can also use the special `listenAndServe` function that will automatically create an endpoint and instantiate your handler:
```cpp
int main() {
Http::listenAndServe<HelloHandler>("*:9080");
}
```
And that’s it, now you can fire up your favorite curl request and observe the final result:
```shell
curl http://localhost:9080/
Hello, World
```
Complete code for this example can be found on GitHub: [examples/hello_server.cc](https://github.com/pistacheio/pistache/blob/master/examples/hello_server.cc)
---
title: REST description
---
Documentation writing for this part is still in progress, please refer to the [rest_description](https://github.com/pistacheio/pistache/blob/master/examples/rest_description.cc) example.
---
title: Routing
---
HTTP routing consists of binding an HTTP route to a C++ callback. A special component called an HTTP router will be in charge of dispatching HTTP requests to the right C++ callback. A route is composed of an HTTP verb associated to a resource:
```javascript
GET /users/1
```
Here, `GET` is the verb and `/users/1` is the associated resource.
## HTTP methods
A bunch of HTTP methods (verbs) are supported by Pistache:
- _GET_: The `GET` method is used by the client (e.g browser) to retrieve a resource identified by an URI. For example, to retrieve an user identified by an id, a client will issue a `GET` to the `/users/:id` Request-URI.
- _POST_: the `POST` method is used to post or send new information to a certain resource. The server will then read and store the data associated to the request. `POST` is a common way of transmitting data from an HTML form. `POST` can also be used to create a new resource or update information of an existing resource. For example, to create a new user, a client will issue a `POST` to the `/users` path with the data of the user to create in its body.
- _PUT_: `PUT` is very similar to `POST` except that `PUT` is idempotent, meaning that two requests to the same Request-URI with the same identical content should have the same effect and should produce the same result.
- _DELETE_: the `DELETE` method is used to delete a resource associated to a given Request-URI. For example, to remove an user, a client might issue a `DELETE` call to the `/users/:id` Request-URI.
To sum up, `POST` and `PUT` are used to Create and/or Update, `GET` is used to Read and `DELETE` is used to Delete information.
## Route patterns
### Static routes
Static routes are the simplest ones as they do rely on dynamic parts of the Request-URI. For example `/users/all` is a static route that will exactly match the `/users/all` Request-URI.
### Dynamic routes
However, it is often useful to define routes that have dynamic parts. For example, to retrieve a specific user by its id, the id is needed to query the storage. Dynamic routes thus have parameters that are then matched one by one by the HTTP router. In a dynamic route, parameters are identified by a column `:`
`/users/:id`
Here, `:id` is a dynamic parameter. When a request comes in, the router will try to match the `:id` parameter to the corresponding part of the request. For example, if the server receives a request to `/users/13`, the router will match the `13` value to the `:id` parameter.
Some parameters, like `:id` are named. However, Pistache also allows _splat_ (wildcard) parameters, identified by a star `*`:
`/link/*/to/*`
## Defining routes
To define your routes, you first have to instantiate an HTTP router:
```cpp
Http::Router router;
```
Then, use the `Routes::<Method>()` functions to add some routes:
```cpp
Routes::Get(router, "/users/all", Routes::bind(&UsersApi::getAllUsers, this));
Routes::Post(router, "/users/:id", Routes::bind(&UsersApi::getUserId, this));
Routes::Get(router, "/link/*/to/*", Routes::bind(&UsersApi::linkUsers, this));
```
`Routes::bind` is a special function that will generate a corresponding C++ callback that will then be called by the router if a given route matches the Request-URI.
### Callbacks
A C++ callback associated to a route must have the following signature:
```cpp
void(const Rest::Request&, Http::ResponseWriter);
```
A callback can either be a non-static free or member function. For member functions, a pointer to the corresponding instance must be passed to the Routes::bind function so that the router knows on which instance to invoke the member function.
The first parameter of the callback is `Rest::Request` and not an `Http::Request`. A `Rest::Request` is an `Http::Request` with additional functions. Named and splat parameters are for example retrieved through this object:
```cpp
void UsersApi::getUserId(const Rest::Request& request, Http::ResponseWriter response) {
auto id = request.param(":id").as<int>();
// ...
}
void UsersApi::linkUsers(const Rest::Request& request, Http::ResponseWriter response) {
auto u1 = request.splatAt(0).as<std::string>();
auto u2 = request.splatAt(1).as<std::string>();
// ...
}
```
As you can see, parameters are also typed. To cast a parameter to the appropriate type, use the `as<T>` member template.
:::note Cast safety
An exception will be thrown if the parameter can not be casted to the right type
:::
### Installing the handler
Once the routes have been defined, the final `Http::Handler` must be set to the HTTP Endpoint. To retrieve the handler, just call the `handler()` member function on the router object:
```cpp
endpoint.setHandler(router.handler());
```
module.exports = {
title: 'Pistache',
tagline: 'An elegant C++ REST framework.',
url: 'https://pistache.io',
baseUrl: '/',
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
favicon: 'img/logo.png',
organizationName: 'pistacheio', // Usually your GitHub org/user name.
projectName: 'pistace', // Usually your repo name.
themeConfig: {
navbar: {
title: 'Pistache',
logo: {
alt: 'Pistache logo',
src: 'img/logo.png',
},
items: [
{
to: 'docs/',
activeBasePath: 'docs',
label: 'Docs',
position: 'left',
},
{
href: 'https://github.com/pistacheio/pistache',
className: 'header-github-link',
'aria-label': 'GitHub repository',
position: 'right',
},
],
},
footer: {
style: 'dark',
links: [
{
title: 'Docs',
items: [
{
label: 'Quickstart',
to: 'docs/',
},
{
label: 'User guide',
to: 'docs/http-handler/',
},
],
},
{
title: 'Community',
items: [
{
label: 'Stack Overflow',
href: 'https://stackoverflow.com/questions/tagged/pistache',
},
{
label: '#pistache on Freenode',
href: 'irc://chat.freenode.net',
},
],
},
{
title: 'More',
items: [
{
label: 'GitHub',
href: 'https://github.com/pistacheio/pistache',
},
],
},
],
copyright: `Pistache, 2015 - ${new Date().getFullYear()}`,
},
},
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.js'),
// Please change this to your repo.
editUrl:
'https://github.com/pistacheio/pistache/edit/master/pistache.io/',
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
};
{
"name": "pistache-io",
"version": "0.0.0",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"serve": "docusaurus serve",
"clear": "docusaurus clear"
},
"dependencies": {
"@docusaurus/core": "2.0.0-alpha.70",
"@docusaurus/preset-classic": "2.0.0-alpha.70",
"@mdx-js/react": "^1.6.21",
"clsx": "^1.1.1",
"react": "^16.8.4",
"react-dom": "^16.8.4"
},
"browserslist": {
"production": [
">0.5%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
\ No newline at end of file
module.exports = {
leftSidebar: {
Pistache: ['quickstart', 'http-handler', 'asynchronous-http-programming', 'headers', 'routing'],
},
};
/* stylelint-disable docusaurus/copyright-header */
/**
* Any CSS included here will be global. The classic template
* bundles Infima by default. Infima is a CSS framework designed to
* work well for content-centric websites.
*/
/* You can override the default Infima variables here. */
:root {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: rgb(33, 175, 144);
--ifm-color-primary-darker: rgb(31, 165, 136);
--ifm-color-primary-darkest: rgb(26, 136, 112);
--ifm-color-primary-light: rgb(70, 203, 174);
--ifm-color-primary-lighter: rgb(102, 212, 189);
--ifm-color-primary-lightest: rgb(146, 224, 208);
--ifm-code-font-size: 95%;
}
.docusaurus-highlight-code-line {
background-color: rgb(72, 77, 91);
display: block;
margin: 0 calc(-1 * var(--ifm-pre-padding));
padding: 0 var(--ifm-pre-padding);
}
.header-github-link:hover {
opacity: 0.6;
}
.header-github-link:before {
content: '';
width: 24px;
height: 24px;
display: flex;
background: url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12'/%3E%3C/svg%3E")
no-repeat;
}
html[data-theme='dark'] .header-github-link:before {
background: url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='white' d='M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12'/%3E%3C/svg%3E")
no-repeat;
}
import React from 'react';
import clsx from 'clsx';
import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
import styles from './styles.module.css';
const features = [
{
title: 'Modern API',
imageUrl: 'img/undraw_futuristic_interface.svg',
description: (
<>
Written in pure C++17 and providing a low-level HTTP abstraction,
Pistache makes playing with its modern API fun and easy,
just take a look at the quickstart
</>
),
},
{
title: 'What\'s in the box',
imageUrl: 'img/undraw_accept_request.svg',
description: (
<>
<ul>
<li>A multi-threaded HTTP server to build your APIs</li>
<li>An asynchronous HTTP client to request APIs</li>
<li>An HTTP router to dispatch requests to C++ functions</li>
<li>A REST description DSL to easily define your APIs</li>
<li>Type-safe headers and MIME types implementation</li>
</ul>
</>
),
},
{
title: 'Use it',
imageUrl: 'img/undraw_version_control.svg',
description: (
<>
<ul>
<li>Clone it on <a href="https://github.com/pistacheio/pistache">GitHub</a></li>
<li>Start with the <a href="docs/">quickstart</a></li>
<li>Read the full user's <a href="docs/http-handler">guide</a></li>
<li>Have issues with it? Fill an <a href="https://github.com/pistacheio/pistache/issues">issue</a></li>
</ul>
</>
),
},
];
function Feature({imageUrl, title, description}) {
const imgUrl = useBaseUrl(imageUrl);
return (
<div className={clsx('col col--4', styles.feature)}>
{imgUrl && (
<div className="text--center">
<img className={styles.featureImage} src={imgUrl} alt={title} />
</div>
)}
<h3>{title}</h3>
<p>{description}</p>
</div>
);
}
function Home() {
const context = useDocusaurusContext();
const {siteConfig = {}} = context;
return (
<Layout
description="Description will go into a meta tag in <head />">
<header className={clsx('hero hero--primary', styles.heroBanner)}>
<div className="container">
<h1 className="hero__title">{siteConfig.title}</h1>
<p className="hero__subtitle">{siteConfig.tagline}</p>
<div className={styles.buttons}>
<Link
className={clsx(
'button button--outline button--secondary button--lg',
styles.getStarted,
)}
to={useBaseUrl('docs/')}>
Get Started
</Link>
</div>
</div>
</header>
<main>
{features && features.length > 0 && (
<section className={styles.features}>
<div className="container">
<div className="row">
{features.map((props, idx) => (
<Feature key={idx} {...props} />
))}
</div>
</div>
</section>
)}
</main>
</Layout>
);
}
export default Home;
/* stylelint-disable docusaurus/copyright-header */
/**
* CSS files with the .module.css suffix will be treated as CSS modules
* and scoped locally.
*/
.heroBanner {
padding: 4rem 0;
text-align: center;
position: relative;
overflow: hidden;
}
@media screen and (max-width: 966px) {
.heroBanner {
padding: 2rem;
}
}
.buttons {
display: flex;
align-items: center;
justify-content: center;
}
.features {
display: flex;
align-items: center;
padding: 2rem 0;
width: 100%;
}
.featureImage {
height: 200px;
width: 200px;
}
This diff is collapsed.
This diff is collapsed.
<svg id="f9966515-f79a-4354-a0fc-c22822ae3a36" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" width="688.13386" height="510.5" viewBox="0 0 688.13386 510.5"><path d="M903.2874,655.4311a24.14567,24.14567,0,0,0-.00018,48.29134h.00018a24.14567,24.14567,0,0,0,0-48.29134Z" transform="translate(-255.93307 -194.75)" fill="#ccc"/><path id="eddccf5f-d02a-4888-86ae-be237287dc7c" data-name="Path 395" d="M900.99634,689.60463a2.93038,2.93038,0,0,1-1.76292-.5859l-.03154-.02365-6.64007-5.07945a2.9508,2.9508,0,1,1,3.59065-4.6836l4.30091,3.29814L910.61664,669.271a2.94955,2.94955,0,0,1,4.13542-.54623l.00086.00064-.06308.08758.06479-.08758a2.95312,2.95312,0,0,1,.54559,4.13625L903.346,688.45037a2.95134,2.95134,0,0,1-2.34705,1.15076Z" transform="translate(-255.93307 -194.75)" fill="#fff"/><polygon points="594.783 499.316 583.351 499.315 577.915 455.219 594.787 455.221 594.783 499.316" fill="#ffb8b8"/><path d="M575.185,496.04845h22.04781a0,0,0,0,1,0,0V509.9304a0,0,0,0,1,0,0H561.30307a0,0,0,0,1,0,0v0A13.88193,13.88193,0,0,1,575.185,496.04845Z" fill="#2f2e41"/><polygon points="549.283 499.316 537.851 499.315 532.415 455.219 549.287 455.221 549.283 499.316" fill="#ffb8b8"/><path d="M529.685,496.04845h22.04781a0,0,0,0,1,0,0V509.9304a0,0,0,0,1,0,0H515.80307a0,0,0,0,1,0,0v0A13.88193,13.88193,0,0,1,529.685,496.04845Z" fill="#2f2e41"/><path d="M859.52294,541.61574a9.377,9.377,0,0,1,1.97613-14.242l-3.54085-21.13341,12.3179-5.28408,4.58121,29.9147a9.42779,9.42779,0,0,1-15.33439,10.74481Z" transform="translate(-255.93307 -194.75)" fill="#ffb8b8"/><path d="M763.085,531.63a9.377,9.377,0,0,0,.40388-14.37279l6.98357-20.258-11.27569-7.24646-9.46034,28.7468A9.42779,9.42779,0,0,0,763.085,531.63Z" transform="translate(-255.93307 -194.75)" fill="#ffb8b8"/><circle cx="565.70229" cy="163.07971" r="24.56103" fill="#ffb8b8"/><path d="M762.32565,516.47412a4.50216,4.50216,0,0,1-1.24536-.17627l-7.15869-2.05517a4.50764,4.50764,0,0,1-3.08765-5.55127l14.77368-52.16211,20.60205-50.5752c2.04859-5.02783,6.32862-8.32519,11.16992-8.605a11.44643,11.44643,0,0,1,10.77808,6.27686h0a15.62084,15.62084,0,0,1,.35693,13.7705l-23.417,51.21045-18.61621,45.0835A4.49773,4.49773,0,0,1,762.32565,516.47412Z" transform="translate(-255.93307 -194.75)" fill="#b6ce5d"/><path d="M835.49548,378.427l-13.64656.24261a9.07354,9.07354,0,0,1-8.8959-11.58969,21.127,21.127,0,0,0,.65552-3.01274,15.22492,15.22492,0,0,0,.08978-3.35353,4.952,4.952,0,0,0-9.55443-1.40837v0c-2.29461.03269-7.18294-.71534-9.47755-.68265-4.87206-12.48982,5.74491-28.83323,17.17382-34.97183,11.65126-6.258,26.77521.10869,31.24139,13.15167,6.19839.11141,11.23462,6.22466,12.03341,13.10631s-2.03239,14.06747-6.36329,19.3418S838.73416,378.36942,835.49548,378.427Z" transform="translate(-255.93307 -194.75)" fill="#2f2e41"/><path d="M790.63742,689.94922a4.51451,4.51451,0,0,1-4.46143-4.00977L781.11251,515.7041l63.78736,4.54053.04907.41016c14.41479,120.66259,9.4873,162.43164,9.43579,162.83935a4.49832,4.49832,0,0,1-5.07544,4.20264l-14.09668.33789a4.49787,4.49787,0,0,1-3.989-4.2959L818.05221,560.439a1.40645,1.40645,0,0,0-1.46606-1.05615,1.46265,1.46265,0,0,0-1.43921,1.17725l-5.08862,123.70361a4.48067,4.48067,0,0,1-4.04126,4.67041l-14.93238.99268A4.459,4.459,0,0,1,790.63742,689.94922Z" transform="translate(-255.93307 -194.75)" fill="#2f2e41"/><path d="M817.10592,536.04492c-.38159,0-.76245-.00586-1.145-.01758-18.34179-.55224-32.69165-14.4292-36.65258-18.66943a4.47811,4.47811,0,0,1-1.0813-4.09717l10.5813-44.76416-2.80738-38.917a38.36931,38.36931,0,0,1,10.50562-29.6333,31.66346,31.66346,0,0,1,24.38647-9.86572c17.855.852,31.94141,16.81152,32.06861,36.33252.19751,30.23486-.69263,32.312-.98487,32.99462-8.91089,20.79688-4.04419,49.98926-2.34033,58.44141a4.5164,4.5164,0,0,1-1.33716,4.1875C838.499,531.33545,828.00924,536.04443,817.10592,536.04492Z" transform="translate(-255.93307 -194.75)" fill="#b6ce5d"/><path d="M863.17062,524.666a4.4966,4.4966,0,0,1-4.38037-3.49414L847.8735,473.61475l-14.63061-54.35743a15.62109,15.62109,0,0,1,2.62719-13.52246,11.45551,11.45551,0,0,1,11.66651-4.41015c4.72876,1.07617,8.40527,5.03515,9.595,10.33252l11.95483,53.229,5.9624,53.94092a4.50858,4.50858,0,0,1-3.96264,4.96484l-7.39991.84424A4.48708,4.48708,0,0,1,863.17062,524.666Z" transform="translate(-255.93307 -194.75)" fill="#b6ce5d"/><path d="M548.93307,246.75h-267a26,26,0,0,1,0-52h267a26,26,0,0,1,0,52Z" transform="translate(-255.93307 -194.75)" fill="#e6e6e6"/><path d="M281.93307,203.25a17.5,17.5,0,0,0,0,35h267a17.5,17.5,0,0,0,0-35Z" transform="translate(-255.93307 -194.75)" fill="#fff"/><path d="M643.2874,196.4311a24.14567,24.14567,0,0,0-.00018,48.29134h.00018a24.14567,24.14567,0,0,0,0-48.29134Z" transform="translate(-255.93307 -194.75)" fill="#b6ce5d"/><path id="ad0a0ef9-b94e-459b-a18b-5e864c4f85bd" data-name="Path 395" d="M640.99634,230.60463a2.93038,2.93038,0,0,1-1.76292-.5859l-.03154-.02365-6.64007-5.07945a2.9508,2.9508,0,1,1,3.59065-4.6836l4.30091,3.29814,10.16327-13.25912a2.94955,2.94955,0,0,1,4.13542-.54623l.00086.00064-.06308.08758.06479-.08758a2.95312,2.95312,0,0,1,.54559,4.13625L643.346,229.45037a2.95134,2.95134,0,0,1-2.34705,1.15076Z" transform="translate(-255.93307 -194.75)" fill="#fff"/><path d="M548.93307,334.75h-267a26,26,0,0,1,0-52h267a26,26,0,0,1,0,52Z" transform="translate(-255.93307 -194.75)" fill="#e6e6e6"/><path d="M281.93307,291.25a17.5,17.5,0,0,0,0,35h267a17.5,17.5,0,0,0,0-35Z" transform="translate(-255.93307 -194.75)" fill="#fff"/><path d="M643.2874,284.4311a24.14567,24.14567,0,0,0-.00018,48.29134h.00018a24.14567,24.14567,0,0,0,0-48.29134Z" transform="translate(-255.93307 -194.75)" fill="#b6ce5d"/><path id="b52aca83-db19-4a50-956a-5cae2a617b83" data-name="Path 395" d="M640.99634,318.60463a2.93038,2.93038,0,0,1-1.76292-.5859l-.03154-.02365-6.64007-5.07945a2.9508,2.9508,0,1,1,3.59065-4.6836l4.30091,3.29814,10.16327-13.25912a2.94955,2.94955,0,0,1,4.13542-.54623l.00086.00064-.06308.08758.06479-.08758a2.95312,2.95312,0,0,1,.54559,4.13625L643.346,317.45037a2.95134,2.95134,0,0,1-2.34705,1.15076Z" transform="translate(-255.93307 -194.75)" fill="#fff"/><path d="M548.93307,422.75h-267a26,26,0,0,1,0-52h267a26,26,0,0,1,0,52Z" transform="translate(-255.93307 -194.75)" fill="#e6e6e6"/><path d="M281.93307,379.25a17.5,17.5,0,0,0,0,35h267a17.5,17.5,0,0,0,0-35Z" transform="translate(-255.93307 -194.75)" fill="#fff"/><path d="M643.2874,372.4311a24.14567,24.14567,0,0,0-.00018,48.29134h.00018a24.14567,24.14567,0,0,0,0-48.29134Z" transform="translate(-255.93307 -194.75)" fill="#e6e6e6"/><path d="M943.06693,705.25h-209a1,1,0,0,1,0-2h209a1,1,0,0,1,0,2Z" transform="translate(-255.93307 -194.75)" fill="#ccc"/></svg>
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
<svg id="b65f622f-853e-450a-b3c6-fb36327b0801" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="897" height="697.83547" viewBox="0 0 897 697.83547"><defs><linearGradient id="b6650c28-d27b-462d-a47d-3aa47119cf7d" x1="369" y1="646" x2="369" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#e4e4e4"/><stop offset="0.4735" stop-color="#f0f0f0" stop-opacity="0.7"/></linearGradient></defs><title>futuristic_interface</title><polygon points="369 646 706.75 0 31.25 0 369 646 706.75 0 31.25 0 369 646" opacity="0.4" fill="url(#b6650c28-d27b-462d-a47d-3aa47119cf7d)"/><rect x="323" y="571" width="92" height="92" fill="#3f3d56"/><path d="M525.5,469.08226c-95.94385,0-174-78.05615-174-174s78.05615-174,174-174c95.94434,0,174,78.05616,174,174S621.44434,469.08226,525.5,469.08226Zm0-343c-93.187,0-169,75.813-169,169s75.813,169,169,169c93.18652,0,169-75.813,169-169S618.68652,126.08226,525.5,126.08226Z" transform="translate(-151.5 -101.08226)" fill="#3f3d56"/><path d="M525.5,427.08226c-72.78516,0-132-59.21484-132-132s59.21484-132,132-132,132,59.21485,132,132S598.28516,427.08226,525.5,427.08226Zm0-261a129,129,0,1,0,129,129A129.14608,129.14608,0,0,0,525.5,166.08226Z" transform="translate(-151.5 -101.08226)" fill="#3f3d56"/><path d="M525.5,337.08226a42,42,0,1,1,42-42A42.0478,42.0478,0,0,1,525.5,337.08226Zm0-82a40,40,0,1,0,40,40A40.04521,40.04521,0,0,0,525.5,255.08226Z" transform="translate(-151.5 -101.08226)" fill="#3f3d56"/><path d="M515.5,245.08226a41,41,0,0,0-41,41h41Z" transform="translate(-151.5 -101.08226)" fill="#b6ce5d"/><path d="M474.5,304.08226a41,41,0,0,0,41,41v-41Z" transform="translate(-151.5 -101.08226)" fill="#b6ce5d" opacity="0.3"/><path d="M532.5,245.08226v41h41A41,41,0,0,0,532.5,245.08226Z" transform="translate(-151.5 -101.08226)" fill="#b6ce5d" opacity="0.3"/><path d="M532.5,341.08226a41,41,0,0,0,41-41h-41Z" transform="translate(-151.5 -101.08226)" fill="#b6ce5d"/><polygon points="415.406 144.923 413.594 144.077 434.863 98.5 572.5 98.5 572.5 100.5 436.137 100.5 415.406 144.923" fill="#3f3d56"/><rect x="528" y="55" width="78" height="6" fill="#3f3d56"/><rect x="528" y="68" width="78" height="6" fill="#3f3d56"/><rect x="528" y="81" width="78" height="6" fill="#3f3d56"/><rect x="335" y="385" width="78" height="6" fill="#3f3d56"/><rect x="335" y="398" width="78" height="6" fill="#3f3d56"/><rect x="335" y="411" width="78" height="6" fill="#3f3d56"/><polygon points="446 428 444 428 444 272.286 421.15 235.528 422.85 234.472 446 271.714 446 428" fill="#3f3d56"/><polygon points="304 428 302 428 302 271.714 325.151 234.472 326.849 235.528 304 272.286 304 428" fill="#3f3d56"/><rect y="661.99977" width="897" height="2" fill="#2f2e41"/><ellipse cx="689.86344" cy="456.19163" rx="61.54769" ry="15.57231" fill="#2f2e41"/><path d="M817.26344,350.01389s-.74154,29.66154-6.67385,33.36923,10.38154,14.83077,10.38154,14.83077l24.47077-4.44923,15.57231-19.28s-11.12308-13.34769-7.41539-24.47077Z" transform="translate(-151.5 -101.08226)" fill="#ffb6b6"/><path d="M817.26344,350.01389s-.74154,29.66154-6.67385,33.36923,10.38154,14.83077,10.38154,14.83077l24.47077-4.44923,15.57231-19.28s-11.12308-13.34769-7.41539-24.47077Z" transform="translate(-151.5 -101.08226)" opacity="0.1"/><path d="M783.8942,378.93389s-12.60615,5.19077-13.34769,22.98769,0,69.70462,0,69.70462l21.50462-1.48308Z" transform="translate(-151.5 -101.08226)" fill="#f0f0f0"/><rect x="890.6757" y="564.91076" width="1.48318" height="200.88475" transform="translate(-232.0121 23.27841) rotate(-7.63657)" fill="#2f2e41"/><rect x="861.38508" y="568.39837" width="1.48287" height="197.24645" transform="translate(-205.94658 -24.03837) rotate(-4.9604)" fill="#2f2e41"/><rect x="684.23868" y="650.89295" width="227.48952" height="1.48344" transform="translate(-74.9162 1286.07118) rotate(-84.79038)" fill="#2f2e41"/><rect x="829.42447" y="534.53274" width="1.4826" height="231.1881" transform="translate(-174.32171 -70.83643) rotate(-2.05896)" fill="#2f2e41"/><path d="M763.13113,504.25389s-85.27693,5.93231-71.1877,34.11078,82.31077,75.63692,82.31077,75.63692,12.60616,2.96616,14.83077,3.70769,36.33539-22.24615,36.33539-22.24615-20.76308-12.60615-30.40308-14.83077-37.07692-25.95385-37.07692-25.95385l77.12-19.28-45.23385-38.56Z" transform="translate(-151.5 -101.08226)" fill="#2f2e41"/><path d="M831.35267,522.79236s-48.94154,69.23273-39.30154,96.53483S795.01728,737.097,795.01728,737.097s36.33539,11.86462,36.33539,0,10.38154-95.65846,0-123.83693c0,0,2.22461-17.79692,8.15692-20.76307S866.205,562.0939,866.205,562.0939s22.24615-10.38154,19.28-20.02154S831.35267,522.79236,831.35267,522.79236Z" transform="translate(-151.5 -101.08226)" fill="#2f2e41"/><path d="M865.46344,334.44158A29.66154,29.66154,0,1,1,835.8019,304.78,29.64857,29.64857,0,0,1,865.46344,334.44158Z" transform="translate(-151.5 -101.08226)" fill="#ffb6b6"/><path d="M855.0819,364.10312s44.49231,18.53846,37.81846,42.26769-20.76307,126.06155-42.26769,126.06155-66.73847-11.86462-69.70462-16.31385,11.12308-94.91693,11.12308-94.91693,17.03773-55.15866,23.34963-50.567c0,0-4.06963,23.87164,17.435,17.93933S855.0819,364.10312,855.0819,364.10312Z" transform="translate(-151.5 -101.08226)" fill="#f0f0f0"/><path d="M816.28746,364.10312s-37.584,5.19077-36.101,13.34769l-2.96615,31.14462L789.085,471.6262l-1.48307,20.76308-36.33539,12.60615,43.00923,12.60616s17.79693-85.27693,14.83077-101.59078S816.28746,364.10312,816.28746,364.10312Z" transform="translate(-151.5 -101.08226)" fill="#3f3d56"/><path d="M853.92988,361.47662s40.45356,23.38958,43.41971,30.805,0,78.60308,0,78.60308,5.19077,66.73847-9.64,83.79385c0,0,5.19077-8.89846-22.24615-8.89846s-40.78462-5.19077-41.52616-5.93231-14.83077,0-14.83077,0-5.19077-106.04,11.86462-125.32S856.48556,372.93936,853.92988,361.47662Z" transform="translate(-151.5 -101.08226)" fill="#3f3d56"/><path d="M774.99574,517.60159v8.89846S745.3342,553.937,757.19882,561.35236,792.05113,534.657,792.05113,534.657l2.79373-19.82038Z" transform="translate(-151.5 -101.08226)" fill="#ffb6b6"/><path d="M774.99574,517.60159v8.89846S745.3342,553.937,757.19882,561.35236,792.05113,534.657,792.05113,534.657l2.79373-19.82038Z" transform="translate(-151.5 -101.08226)" opacity="0.1"/><path d="M786.86036,611.777l8.15692,11.86461s-28.17846,43.00923-15.57231,47.45847,67.48-48.94154,66.73847-53.39078-26.69539-22.24615-26.69539-22.24615Z" transform="translate(-151.5 -101.08226)" fill="#2f2e41"/><path d="M797.2419,731.16467l-6.67385,29.66154S764.6142,794.937,776.47882,797.90314s38.56-.74154,42.26769-8.89846,8.15693-19.28,14.08924-28.17847-5.19077-29.66154-5.19077-29.66154Z" transform="translate(-151.5 -101.08226)" fill="#2f2e41"/><path d="M775.73728,458.27851l-5.19077,13.34769,2.22462,51.16616s18.53846-7.41539,24.47077,0l-5.19077-51.16616-8.15693-13.34769Z" transform="translate(-151.5 -101.08226)" fill="#f0f0f0"/><path d="M803.17421,522.79236,789.085,527.24159s-54.87384,17.79692-30.40307,30.40308,38.56-8.15693,38.56-8.15693l9.64-7.41538Z" transform="translate(-151.5 -101.08226)" fill="#ffb6b6"/><path d="M886.22652,394.5062s-20.02154,9.64-22.9877,35.59385-6.67384,60.06461-6.67384,60.06461l-37.07693,24.47077s-25.35557-1.00613-21.57624,8.3954,4.52086,29.42307,11.1947,26.45691,16.31385-20.76307,25.95385-21.50461,49.68308-16.31385,54.13231-34.11077,21.50462-77.86155,14.08923-86.76S892.15882,390.79851,886.22652,394.5062Z" transform="translate(-151.5 -101.08226)" fill="#f0f0f0"/><path d="M807.72963,315.53439s-11.86793-.18007-14.455,4.40382-1.73733,7.90776,1.77072,7.9915,19.84273-9.54028,19.84273-9.54028Z" transform="translate(-151.5 -101.08226)" fill="#3f3d56"/><path d="M807.72963,315.53439s-11.86793-.18007-14.455,4.40382-1.73733,7.90776,1.77072,7.9915,19.84273-9.54028,19.84273-9.54028Z" transform="translate(-151.5 -101.08226)" opacity="0.1"/><path d="M859.60518,330.70972l-8.11712,7.03281s-7.70687,7.14583-18.80029-3.85562-26.78332-19.73817-33.24686-17.10507l16.477-6.93648,16.01229-.44365,18.19327,7.66089Z" transform="translate(-151.5 -101.08226)" fill="#3f3d56"/><path d="M865.14559,338.63636a101.03216,101.03216,0,0,0-10.18541-9.98768c-6.99642-6.00607-16.887-12.94637-27.40669-15.37683,0,0-10.55344-3.349-18.06354-.1215l14.52209-15.8615s7.84918-4.45828,11.95167-3.328c0,0,13.80112,2.9682,17.70524,6.43617.11024.0966.21115.195.30384.29118h0a10.09968,10.09968,0,0,1,6.15085,3.33215c3.55357,4.05981,9.14305,12.01729,7.93145,20.85172C866.30518,337.63168,865.14559,338.63636,865.14559,338.63636Z" transform="translate(-151.5 -101.08226)" fill="#3f3d56"/><path d="M857.68163,332.52944c-29.89472-25.19022-46.88638-19.712-47.05438-19.65367l-.49171-1.39907c.71475-.252,17.86717-5.895,48.502,19.91871Z" transform="translate(-151.5 -101.08226)" opacity="0.1"/><ellipse cx="853.22805" cy="299.96004" rx="2.96615" ry="4.44923" transform="translate(15.34101 787.81492) rotate(-60)" fill="#3f3d56"/><ellipse cx="860.64344" cy="334.81235" rx="2.22462" ry="3.70769" transform="translate(-190.85766 26.83769) rotate(-8.31107)" fill="#ffb6b6"/><path d="M835.29028,354.84869c2.84006-4.74582-1.535-6.785-1.535-6.785s-10.01077-3.64836-13.73331-5.01281c-3.73-1.357-5.46514,4.0117-5.46514,4.0117-.67482.31891-4.73844-2.78077-7.59334-5.65789a29.6728,29.6728,0,0,0,44.24021,18.39014l5.25006-12.68776C849.20771,351.93986,842.14716,354.59152,835.29028,354.84869Zm-4.54572,1.78713a7.30947,7.30947,0,0,1-6.92586,1.92056l.22983-1.24578s4.30087-.215,2.48414-1.31991a33.99815,33.99815,0,0,0-6.28081-2.29138s-1.37192-.49682.01484,1.78714l.77123.94914-.55615.9047s-4.034-2.35808-3.65592-6.444c0,0-.42254-3.71511,4.47893-1.928,4.90907,1.79456,8.44622,3.07741,8.44622,3.07741S833.86649,353.551,830.74456,356.63582Z" transform="translate(-151.5 -101.08226)" fill="#3f3d56"/></svg>
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -12,7 +12,7 @@ set(SOURCE_FILES
)
add_library(pistache OBJECT ${SOURCE_FILES})
set_target_properties(pistache PROPERTIES POSITION_INDEPENDENT_CODE 1)
set_target_properties(pistache PROPERTIES POSITION_INDEPENDENT_CODE ${PISTACHE_PIC})
add_definitions(-DONLY_C_LOCALE=1)
set(PISTACHE_INCLUDE
......@@ -56,7 +56,7 @@ if (BUILD_SHARED_LIBS)
)
endif ()
set_target_properties(pistache_static PROPERTIES
set_target_properties(pistache_static PROPERTIES
OUTPUT_NAME ${Pistache_OUTPUT_NAME}
)
......
......@@ -111,8 +111,6 @@ const HttpMethods httpMethods = {
} // namespace
static constexpr const char *ParserData = "__Parser";
namespace Private {
Step::Step(Message *request) : message(request) {}
......@@ -425,12 +423,12 @@ BodyStep::Chunk::Result BodyStep::Chunk::parse(StreamCursor &cursor) {
if (available + alreadyAppendedChunkBytes < size + 2) {
cursor.advance(available);
message->body_.append(chunkData.rawText(), available);
alreadyAppendedChunkBytes +=available;
alreadyAppendedChunkBytes += available;
return Incomplete;
}
cursor.advance(size - alreadyAppendedChunkBytes);
//trailing EOL
// trailing EOL
cursor.advance(2);
message->body_.append(chunkData.rawText(), size - alreadyAppendedChunkBytes);
......@@ -546,7 +544,9 @@ Version Message::version() const { return version_; }
Code Message::code() const { return code_; }
std::string Message::body() const { return body_; }
const std::string &Message::body() const { return body_; }
std::string Message::body() { return body_; }
const Header::Collection &Message::headers() const { return headers_; }
......@@ -663,21 +663,29 @@ void ResponseStream::ends() {
}
ResponseWriter::ResponseWriter(ResponseWriter &&other)
: response_(std::move(other.response_)), peer_(other.peer_),
buf_(std::move(other.buf_)), transport_(other.transport_),
timeout_(std::move(other.timeout_)), sent_bytes_(0) {}
ResponseWriter::ResponseWriter(Tcp::Transport *transport, Request request,
: response_(std::move(other.response_))
, peer_(other.peer_)
, buf_(std::move(other.buf_))
, transport_(other.transport_)
, timeout_(std::move(other.timeout_))
{}
ResponseWriter::ResponseWriter(Http::Version version, Tcp::Transport *transport,
Handler *handler, std::weak_ptr<Tcp::Peer> peer)
: response_(request.version()), peer_(peer),
buf_(DefaultStreamSize, handler->getMaxResponseSize()),
transport_(transport),
timeout_(transport, handler, std::move(request), peer), sent_bytes_(0) {}
: response_(version)
, peer_(peer)
, buf_(DefaultStreamSize, handler->getMaxResponseSize())
, transport_(transport)
, timeout_(transport, version, handler, peer)
{}
ResponseWriter::ResponseWriter(const ResponseWriter &other)
: response_(other.response_), peer_(other.peer_),
buf_(DefaultStreamSize, other.buf_.maxSize()),
transport_(other.transport_), timeout_(other.timeout_), sent_bytes_(0) {}
: response_(other.response_)
, peer_(other.peer_)
, buf_(DefaultStreamSize, other.buf_.maxSize())
, transport_(other.transport_)
, timeout_(other.timeout_)
{}
void ResponseWriter::setMime(const Mime::MediaType &mime) {
auto ct = response_.headers().tryGet<Header::ContentType>();
......@@ -807,8 +815,10 @@ Async::Promise<ssize_t> ResponseWriter::putOnWire(const char *data,
.then<std::function<Async::Promise<ssize_t>(ssize_t)>,
std::function<void(std::exception_ptr &)>>(
[=](int /*l*/) {
return Async::Promise<ssize_t>([=](
Async::Deferred<ssize_t> /*deferred*/) mutable { return; });
return Async::Promise<ssize_t>(
[=](Async::Deferred<ssize_t> /*deferred*/) mutable {
return;
});
},
[=](std::exception_ptr &eptr) {
......@@ -922,24 +932,24 @@ Private::ParserImpl<Http::Response>::ParserImpl(size_t maxDataSize)
void Handler::onInput(const char *buffer, size_t len,
const std::shared_ptr<Tcp::Peer> &peer) {
auto &parser = getParser(peer);
auto parser = getParser(peer);
auto &request = parser->request;
try {
if (!parser.feed(buffer, len)) {
parser.reset();
if (!parser->feed(buffer, len)) {
parser->reset();
throw HttpError(Code::Request_Entity_Too_Large,
"Request exceeded maximum buffer size");
}
auto state = parser.parse();
auto state = parser->parse();
if (state == Private::State::Done) {
ResponseWriter response(transport(), parser.request, this, peer);
ResponseWriter response(request.version(), transport(), this, peer);
#ifdef LIBSTDCPP_SMARTPTR_LOCK_FIXME
parser.request.associatePeer(peer);
request.associatePeer(peer);
#endif
auto request = parser.request;
request.copyAddress(peer->address());
auto connection = request.headers().tryGet<Header::Connection>();
......@@ -951,19 +961,19 @@ void Handler::onInput(const char *buffer, size_t len,
}
onRequest(request, std::move(response));
parser.reset();
parser->reset();
}
} catch (const HttpError &err) {
ResponseWriter response(transport(), parser.request, this, peer);
ResponseWriter response(request.version(), transport(), this, peer);
response.send(static_cast<Code>(err.code()), err.reason());
parser.reset();
parser->reset();
}
catch (const std::exception &e) {
ResponseWriter response(transport(), parser.request, this, peer);
ResponseWriter response(request.version(), transport(), this, peer);
response.send(Code::Internal_Server_Error, e.what());
parser.reset();
parser->reset();
}
}
......@@ -971,8 +981,6 @@ void Handler::onConnection(const std::shared_ptr<Tcp::Peer> &peer) {
peer->putData(ParserData, std::make_shared<RequestParser>(maxRequestSize_));
}
void Handler::onDisconnection(const std::shared_ptr<Tcp::Peer> & /*peer*/) {}
void Handler::onTimeout(const Request& /*request*/,
ResponseWriter response)
{
......@@ -989,17 +997,25 @@ void Timeout::disarm() {
bool Timeout::isArmed() const { return armed; }
Timeout::Timeout(Tcp::Transport *transport_, Handler *handler_,
Request request_, std::weak_ptr<Tcp::Peer> peer_)
: handler(handler_), request(std::move(request_)), transport(transport_),
armed(false), timerFd(-1), peer(peer_) {}
Timeout::Timeout(Tcp::Transport *transport_, Http::Version version, Handler *handler_,
std::weak_ptr<Tcp::Peer> peer_)
: handler(handler_)
, transport(transport_)
, version(version)
, armed(false)
, timerFd(-1)
, peer(peer_)
{}
void Timeout::onTimeout(uint64_t numWakeup) {
UNUSED(numWakeup)
if (!peer.lock())
auto sp = peer.lock();
if (!sp)
return;
ResponseWriter response(transport, request, handler, peer);
ResponseWriter response(version, transport, handler, peer);
auto parser = Handler::getParser(sp);
const auto& request = parser->request;
handler->onTimeout(request, std::move(response));
}
......@@ -1011,9 +1027,9 @@ void Handler::setMaxResponseSize(size_t value) { maxResponseSize_ = value; }
size_t Handler::getMaxResponseSize() const { return maxResponseSize_; }
RequestParser &
std::shared_ptr<RequestParser>
Handler::getParser(const std::shared_ptr<Tcp::Peer> &peer) {
return *std::static_pointer_cast<RequestParser>(peer->getData(ParserData));
return std::static_pointer_cast<RequestParser>(peer->getData(ParserData));
}
} // namespace Http
......
......@@ -118,7 +118,7 @@ cpu_set_t CpuSet::toPosix() const {
namespace Polling {
Event::Event(Tag _tag) : flags(), fd(-1), tag(_tag) {}
Event::Event(Tag _tag) : flags(), tag(_tag) {}
Epoll::Epoll()
: epoll_fd([&]() { return TRY_RET(epoll_create(Const::MaxEvents)); }()) {}
......@@ -171,7 +171,8 @@ int Epoll::poll(std::vector<Event> &events,
int ready_fds = -1;
do {
ready_fds = ::epoll_wait(epoll_fd, evs, Const::MaxEvents, static_cast<int>(timeout.count()));
ready_fds = ::epoll_wait(epoll_fd, evs, Const::MaxEvents,
static_cast<int>(timeout.count()));
} while (ready_fds < 0 && errno == EINTR);
for (int i = 0; i < ready_fds; ++i) {
......
......@@ -18,6 +18,8 @@
namespace Pistache {
namespace Tcp {
std::atomic<size_t> idCounter{0};
namespace {
struct ConcretePeer : Peer {
ConcretePeer() = default;
......@@ -26,7 +28,7 @@ struct ConcretePeer : Peer {
} // namespace
Peer::Peer(Fd fd, const Address &addr, void *ssl)
: fd_(fd), addr(addr), ssl_(ssl) {}
: fd_(fd), addr(addr), ssl_(ssl), id_(idCounter++) {}
Peer::~Peer() {
#ifdef PISTACHE_USE_SSL
......@@ -66,6 +68,7 @@ const std::string &Peer::hostname() {
}
void *Peer::ssl() const { return ssl_; }
size_t Peer::getID() const { return id_; }
int Peer::fd() const {
if (fd_ == -1) {
......
......@@ -106,13 +106,13 @@ void TransportImpl::checkIdlePeers()
for (const auto& peerPair: peers)
{
const auto& peer = peerPair.second;
auto& parser = Http::Handler::getParser(peer);
auto time = parser.time();
auto parser = Http::Handler::getParser(peer);
auto time = parser->time();
auto now = std::chrono::steady_clock::now();
auto elapsed = now - time;
auto* step = parser.step();
auto* step = parser->step();
if (step->id() == Private::RequestLineStep::Id)
{
if (elapsed > headerTimeout_ || elapsed > bodyTimeout_)
......@@ -127,8 +127,7 @@ void TransportImpl::checkIdlePeers()
for (const auto& idlePeer: idlePeers)
{
Http::Request request;
ResponseWriter response(this, request, static_cast<Http::Handler *>(handler_.get()), idlePeer);
ResponseWriter response(Http::Version::Http11, this, static_cast<Http::Handler *>(handler_.get()), idlePeer);
response.send(Http::Code::Request_Timeout).then([=](ssize_t) {
removePeer(idlePeer);
}, [=](std::exception_ptr) {
......
......@@ -231,7 +231,11 @@ void Listener::bind(const Address &address) {
const addrinfo *addr = nullptr;
for (addr = addr_info.get_info_ptr(); addr; addr = addr->ai_next) {
fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
auto socktype = addr->ai_socktype;
if (options_.hasFlag(Options::CloseOnExec))
socktype |= SOCK_CLOEXEC;
fd = ::socket(addr->ai_family, socktype, addr->ai_protocol);
if (fd < 0)
continue;
......
......@@ -12,9 +12,9 @@
namespace Pistache {
namespace Rest {
Request::Request(const Http::Request &request, std::vector<TypedParam> &&params,
Request::Request(Http::Request request, std::vector<TypedParam> &&params,
std::vector<TypedParam> &&splats)
: Http::Request(request), params_(std::move(params)),
: Http::Request(std::move(request)), params_(std::move(params)),
splats_(std::move(splats)) {}
bool Request::hasParam(const std::string &name) const {
......@@ -303,8 +303,11 @@ RouterHandler::RouterHandler(std::shared_ptr<Rest::Router> router)
void RouterHandler::onRequest(const Http::Request &req,
Http::ResponseWriter response) {
auto resp = response.clone();
router->route(req, std::move(resp));
router->route(req, std::move(response));
}
void RouterHandler::onDisconnection(const std::shared_ptr<Tcp::Peer> &peer) {
router->disconnectPeer(peer);
}
} // namespace Private
......@@ -385,6 +388,10 @@ void Router::addMiddleware(Route::Middleware middleware) {
middlewares.push_back(std::move(middleware));
}
void Router::addDisconnectHandler(Route::DisconnectHandler handler) {
disconnectHandlers.push_back(std::move(handler));
}
void Router::addNotFoundHandler(Route::Handler handler) {
notFoundHandler = std::move(handler);
}
......@@ -422,7 +429,7 @@ Route::Status Router::route(const Http::Request &http_req,
if (route != nullptr) {
auto params = std::get<1>(result);
auto splats = std::get<2>(result);
route->invokeHandler(Request(req, std::move(params), std::move(splats)),
route->invokeHandler(Request(std::move(req), std::move(params), std::move(splats)),
std::move(resp));
return Route::Status::Match;
}
......@@ -481,6 +488,12 @@ void Router::addRoute(Http::Method method, const std::string &resource,
r.addRoute(path, handler, ptr);
}
void Router::disconnectPeer(const std::shared_ptr<Tcp::Peer> &peer) {
for (const auto &handler : disconnectHandlers) {
handler(peer);
}
}
namespace Routes {
void Get(Router &router, const std::string &resource, Route::Handler handler) {
......
......@@ -3,12 +3,15 @@
#include <pistache/common.h>
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/peer.h>
#include "gtest/gtest.h"
#include <chrono>
#include <condition_variable>
#include <fstream>
#include <future>
#include <mutex>
#include <string>
#include "tcp_client.h"
......@@ -506,3 +509,87 @@ TEST(http_server_test, client_request_body_timeout_raises_http_408) {
server.shutdown();
}
namespace {
class WaitHelper {
public:
void increment() {
std::lock_guard<std::mutex> lock(counterLock_);
++counter_;
cv_.notify_one();
}
template <typename Duration>
bool wait(const size_t count, const Duration timeout) {
std::unique_lock<std::mutex> lock(counterLock_);
return cv_.wait_for(lock, timeout,
[this, count]() { return counter_ >= count; });
}
private:
size_t counter_ = 0;
std::mutex counterLock_;
std::condition_variable cv_;
};
struct ClientCountingHandler : public Http::Handler {
HTTP_PROTOTYPE(ClientCountingHandler)
explicit ClientCountingHandler(std::shared_ptr<WaitHelper> waitHelper)
: waitHelper(waitHelper) {
std::cout << "[server] Ininting..." << std::endl;
}
void onRequest(const Http::Request &request,
Http::ResponseWriter writer) override {
auto peer = writer.getPeer();
if (peer) {
activeConnections.insert(peer->getID());
} else {
return;
}
std::string requestAddress = request.address().host();
writer.send(Http::Code::Ok, requestAddress);
std::cout << "[server] Sent: " << requestAddress << std::endl;
}
void onDisconnection(const std::shared_ptr<Tcp::Peer> &peer) override {
std::cout << "[server] Disconnect from peer ID " << peer->getID()
<< " connecting from " << peer->address().host() << std::endl;
activeConnections.erase(peer->getID());
waitHelper->increment();
}
private:
std::unordered_set<size_t> activeConnections;
std::shared_ptr<WaitHelper> waitHelper;
};
} // namespace
TEST(http_server_test, client_multiple_requests_disconnects_handled) {
const Pistache::Address address("localhost", Pistache::Port(0));
Http::Endpoint server(address);
auto flags = Tcp::Options::ReuseAddr;
auto server_opts = Http::Endpoint::options().flags(flags);
server.init(server_opts);
std::cout << "Trying to run server...\n";
auto waitHelper = std::make_shared<WaitHelper>();
auto handler = Http::make_handler<ClientCountingHandler>(waitHelper);
server.setHandler(handler);
server.serveThreaded();
const std::string server_address = "localhost:" + server.getPort().toString();
std::cout << "Server address: " << server_address << "\n";
const size_t CLIENT_REQUEST_SIZE = 3;
clientLogicFunc(CLIENT_REQUEST_SIZE, server_address, 1, 6);
const bool result =
waitHelper->wait(CLIENT_REQUEST_SIZE, std::chrono::seconds(2));
server.shutdown();
ASSERT_EQ(result, true);
}
......@@ -95,17 +95,14 @@ SocketWrapper bind_free_port() {
return SocketWrapper(sockfd);
}
// This is just done to get the value of a free port. The socket will be
// closed after the closing curly bracket and the port will be free again
// (SO_REUSEADDR option). In theory, it is possible that some application grab
// this port before we bind it again...
uint16_t get_free_port() { return bind_free_port().port(); }
TEST(listener_test, listener_bind_port_free) {
uint16_t port_nb;
// This is just done to get the value of a free port. The socket will be
// closed after the closing curly bracket and the port will be free again
// (SO_REUSEADDR option). In theory, it is possible that some application grab
// this port before we bind it again...
{
SocketWrapper s = bind_free_port();
port_nb = s.port();
}
uint16_t port_nb = get_free_port();
if (port_nb == 0) {
FAIL() << "Could not find a free port. Abort test.\n";
......@@ -125,16 +122,7 @@ TEST(listener_test, listener_bind_port_free) {
// Listener should not crash if an additional member is added to the listener
// class. This test is there to prevent regression for PR 303
TEST(listener_test, listener_uses_default) {
uint16_t port_nb;
// This is just done to get the value of a free port. The socket will be
// closed after the closing curly bracket and the port will be free again
// (SO_REUSEADDR option). In theory, it is possible that some application grab
// this port before we bind it again...
{
SocketWrapper s = bind_free_port();
port_nb = s.port();
}
uint16_t port_nb = get_free_port();
if (port_nb == 0) {
FAIL() << "Could not find a free port. Abort test.\n";
......@@ -215,3 +203,72 @@ TEST(listener_test, listener_bind_ephemeral_v6_port) {
}
ASSERT_TRUE(true);
}
class CloseOnExecTest : public testing::Test {
public:
~CloseOnExecTest() override = default;
std::unique_ptr<Pistache::Tcp::Listener>
prepare_listener(const Pistache::Tcp::Options options) {
const Pistache::Address address(Pistache::Ipv4::any(),
Pistache::Port(port));
auto listener = std::make_unique<Pistache::Tcp::Listener>(address);
listener->setHandler(Pistache::Http::make_handler<DummyHandler>());
listener->init(1, Pistache::Flags<Pistache::Tcp::Options>(options));
return listener;
}
bool is_child_process(pid_t id) {
constexpr auto fork_child_pid = 0;
return id == fork_child_pid;
}
/*
* we need to leak the socket through child process and verify that socket is
* still bound after child has quit
*/
void try_to_leak_socket(const Pistache::Tcp::Options options) {
pid_t id = fork();
if (is_child_process(id)) {
auto server = prepare_listener(options);
server->bind();
std::system(
"sleep 10 <&- &"); // leak open socket to child of our child process
exit(0);
}
int status = 0;
wait(&status);
ASSERT_EQ(0, status);
usleep(100000); // wait 100 ms, so socket gets a chance to be closed
}
uint16_t port = get_free_port();
};
TEST_F(CloseOnExecTest, socket_not_leaked) {
Pistache::Tcp::Options options =
Pistache::Tcp::Options::CloseOnExec | Pistache::Tcp::Options::ReuseAddr;
try_to_leak_socket(options);
ASSERT_NO_THROW({
auto server = prepare_listener(options);
server->bind();
server->shutdown();
});
}
TEST_F(CloseOnExecTest, socket_leaked) {
Pistache::Tcp::Options options = Pistache::Tcp::Options::ReuseAddr;
try_to_leak_socket(options);
ASSERT_THROW(
{
auto server = prepare_listener(options);
server->bind();
server->shutdown();
},
std::runtime_error);
}
......@@ -379,3 +379,67 @@ TEST(segment_tree_node_test, test_resource_sanitize) {
ASSERT_EQ(SegmentTreeNode::sanitizeResource("/path//to/bar"), "path/to/bar");
ASSERT_EQ(SegmentTreeNode::sanitizeResource("/path/to///////:place"), "path/to/:place");
}
namespace {
class WaitHelper {
public:
void increment() {
std::lock_guard<std::mutex> lock(counterLock_);
++counter_;
cv_.notify_one();
}
template <typename Duration>
bool wait(const size_t count, const Duration timeout) {
std::unique_lock<std::mutex> lock(counterLock_);
return cv_.wait_for(lock, timeout,
[this, count]() { return counter_ >= count; });
}
private:
size_t counter_ = 0;
std::mutex counterLock_;
std::condition_variable cv_;
};
TEST(router_test, test_client_disconnects) {
Address addr(Ipv4::any(), 0);
auto endpoint = std::make_shared<Http::Endpoint>(addr);
auto opts = Http::Endpoint::options().threads(1).maxRequestSize(4096);
endpoint->init(opts);
int count_found = 0;
WaitHelper count_disconnect;
Rest::Router router;
Routes::Head(router, "/moogle",
[&count_found](const Pistache::Rest::Request &,
Pistache::Http::ResponseWriter response) {
count_found++;
response.send(Pistache::Http::Code::Ok);
return Pistache::Rest::Route::Result::Ok;
});
router.addDisconnectHandler(
[&count_disconnect](const std::shared_ptr<Tcp::Peer> &) {
count_disconnect.increment();
});
endpoint->setHandler(router.handler());
endpoint->serveThreaded();
const auto bound_port = endpoint->getPort();
{
httplib::Client client("localhost", bound_port);
count_found = 0;
client.Head("/moogle");
ASSERT_EQ(count_found, 1);
}
const bool result = count_disconnect.wait(1, std::chrono::seconds(2));
endpoint->shutdown();
ASSERT_EQ(result, 1);
}
} // namespace
VERSION_MAJOR 0
VERSION_MINOR 0
VERSION_PATCH 002
VERSION_GIT_DATE 20200802
VERSION_GIT_DATE 20210107
SONAME_VERSION_MAJOR 0
SONAME_VERSION_MINOR 0
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment