SNode.C
Loading...
Searching...
No Matches
StaticMiddleware.cpp
Go to the documentation of this file.
1/*
2 * SNode.C - A Slim Toolkit for Network Communication
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2020, 2021, 2022, 2023, 2024, 2025
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20/*
21 * MIT License
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42#include "express/middleware/StaticMiddleware.h"
43
44#include "core/socket/stream/SocketConnection.h"
45#include "web/http/server/SocketContext.h"
46
47#ifndef DOXYGEN_SHOULD_SKIP_THIS
48
49#include "log/Logger.h"
50
51#include <map>
52
53#endif /* DOXYGEN_SHOULD_SKIP_THIS */
54
55namespace express::middleware {
56
57 StaticMiddleware::StaticMiddleware(const std::string& root)
58 : root(root)
59 , index("index.html") {
61
62 use(
63 [&stdHeaders = this->stdHeaders, &stdCookies = this->stdCookies, &connectionState = this->defaultConnectionState] MIDDLEWARE(
64 req, res, next) {
65 LOG(DEBUG) << res->getSocketContext()->getSocketConnection()->getConnectionName() << " Express " << req->method;
66
67 if (req->method == "GET") {
68 if (connectionState == web::http::ConnectionState::Close) {
69 res->set("Connection", "close");
70 } else if (connectionState == web::http::ConnectionState::Keep) {
71 res->set("Connection", "keep-alive");
72 }
73 res->set(stdHeaders);
74
75 for (auto& [value, options] : stdCookies) {
76 res->cookie(value, options.getValue(), options.getOptions());
77 }
78 next();
79 } else {
80 res->sendStatus(405, "Unsupported method: " + req->method + "\n");
81 }
82 },
83 [&index = this->index] MIDDLEWARE(req, res, next) {
84 if (req->url.ends_with("/")) {
85 if (!index.empty()) {
87 << " Express StaticMiddleware Redirecting: " << req->url << " -> " << req->url + index;
88 res->redirect(308, req->url + index);
89 } else {
90 res->status(404).send("Unsupported resource: " + req->url + "\n");
91 }
92 } else {
93 next();
94 }
95 },
96 [&root = this->root] MIDDLEWARE(req, res, next) {
97 const bool fileAllowed = true;
98
99 if (fileAllowed) {
100 res->sendFile(root + req->url, [&root, req, res](int ret) {
101 if (ret == 0) {
103 << " Express StaticMiddleware: GET " << req->url + " -> " << root + req->url;
104 } else {
106 << " Express StaticMiddleware " << req->url + " -> " << root + req->url;
107
108 res->sendStatus(404);
109 }
110 });
111 } else {
112 next();
113 }
114 });
115 }
116
117 class StaticMiddleware& StaticMiddleware::setIndex(const std::string& index) {
118 this->index = index;
119
120 return *this;
121 }
122
123 class StaticMiddleware& StaticMiddleware::clearStdHeaders() {
124 this->stdHeaders.clear();
125
126 return *this;
127 }
128
129 class StaticMiddleware& StaticMiddleware::setStdHeaders(const std::map<std::string, std::string>& stdHeaders) {
130 this->stdHeaders = stdHeaders;
131
132 return *this;
133 }
134
135 class StaticMiddleware& StaticMiddleware::appendStdHeaders(const std::map<std::string, std::string>& stdHeaders) {
136 this->stdHeaders.insert(stdHeaders.begin(), stdHeaders.end());
137
138 return *this;
139 }
140
141 class StaticMiddleware& StaticMiddleware::appendStdHeaders(const std::string& field, const std::string& value) {
142 this->stdHeaders[field] = value;
143
144 return *this;
145 }
146
147 class StaticMiddleware& StaticMiddleware::appendStdCookie(const std::string& name,
148 const std::string& value,
149 const std::map<std::string, std::string>& options) {
150 this->stdCookies.insert({name, web::http::CookieOptions(value, options)});
151
152 return *this;
153 }
154
155 class StaticMiddleware& StaticMiddleware::afterResponse(web::http::ConnectionState connectionState) {
156 this->defaultConnectionState = connectionState;
157
158 return *this;
159 }
160
161 class StaticMiddleware& StaticMiddleware::instance(const std::string& root) {
162 // Keep all created static middlewares alive
163 static std::map<const std::string, std::shared_ptr<class StaticMiddleware>> staticMiddlewares;
164
165 if (!staticMiddlewares.contains(root)) {
166 staticMiddlewares[root] = std::shared_ptr<StaticMiddleware>(new StaticMiddleware(root));
167 }
168
169 return *staticMiddlewares[root];
170 }
171
172 // "Constructor" of StaticMiddleware
173 class StaticMiddleware& StaticMiddleware(const std::string& root) {
174 return StaticMiddleware::instance(root);
175 }
176
177} // namespace express::middleware
#define MIDDLEWARE(req, res, next)
Definition Router.h:63
const std::string & getConnectionName() const
SocketConnection * getSocketConnection() const
void operator()(const std::string &how="") const
Definition Next.cpp:56
std::string url
Definition Request.h:96
std::string method
Definition Request.h:95
Response & cookie(const std::string &name, const std::string &value, const std::map< std::string, std::string > &options={})
Definition Response.cpp:147
void redirect(int state, const std::string &loc, const std::string &html={})
Definition Response.cpp:90
void sendFile(const std::string &file, const std::function< void(int)> &callback)
Definition Response.cpp:181
void sendStatus(int state, const std::string &html={})
Definition Response.cpp:95
Response & set(const std::string &field, const std::string &value, bool overwrite=true)
Definition Response.cpp:129
void send(const std::string &chunk)
Definition Response.cpp:169
Response & status(int status)
Definition Response.cpp:117
Response & set(const std::map< std::string, std::string > &headers, bool overwrite=true)
Definition Response.cpp:135
web::http::server::SocketContext * getSocketContext() const
Definition Response.cpp:68
const Router & setStrictRouting(bool strictRouting=true) const
Definition Router.cpp:78
const std::map< std::string, std::string > & getOptions() const
CookieOptions(const std::string &value, const std::map< std::string, std::string > &options)
const std::string & getValue() const