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, 2026
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/http_utils.h"
46#include "web/http/server/SocketContext.h"
47
48#ifndef DOXYGEN_SHOULD_SKIP_THIS
49
50#include "log/Logger.h"
51
52#include <map>
53
54#endif /* DOXYGEN_SHOULD_SKIP_THIS */
55
56namespace express::middleware {
57
58 StaticMiddleware::StaticMiddleware(const std::string& root, bool fallThrough)
59 : root(root)
60 , index("index.html")
61 , fallThrough(fallThrough) {
63
64 use(
65 [&stdHeaders = this->stdHeaders,
66 &stdCookies = this->stdCookies,
67 &connectionState = this->defaultConnectionState,
68 &fallThrough = this->fallThrough] MIDDLEWARE(req, res, next) {
70
71 if (req->method != "GET") {
72 if (fallThrough) {
73 next("route");
74 } else {
75 res->sendStatus(405, "Unsupported method: " + req->method + "\n");
76 }
77 } else {
78 if (connectionState == web::http::ConnectionState::Close) {
79 res->set("Connection", "close");
80 } else if (connectionState == web::http::ConnectionState::Keep) {
81 res->set("Connection", "keep-alive");
82 }
83 res->set(stdHeaders);
84
85 for (auto& [value, options] : stdCookies) {
86 res->cookie(value, options.getValue(), options.getOptions());
87 }
88
89 next();
90 }
91 },
92 [&index = this->index] MIDDLEWARE(req, res, next) {
93 if (req->path == "/") {
94 if (index.empty()) {
95 res->status(404).send("Unsupported resource: " + req->url + "\n");
96 } else {
98 << " Express StaticMiddleware Redirecting: " << req->url << " -> "
99 << req->originalPath +
100 (!req->originalPath.empty() && req->originalPath.back() != '/' && index.front() != '/' ? "/"
101 : "") +
102 index;
103 res->redirect(
104 308,
105 req->originalPath +
106 (!req->originalPath.empty() && req->originalPath.back() != '/' && index.front() != '/' ? "/" : "") + index);
107 }
108 } else {
109 next();
110 }
111 },
112 [&root = this->root, &fallThrough = this->fallThrough] MIDDLEWARE(req, res, next) {
113 const std::string decodedPath = httputils::url_decode(req->path);
114 res->sendFile(root + decodedPath, [&root, decodedPath, req, res, &next, &fallThrough](int ret) {
115 if (ret == 0) {
117 << " Express StaticMiddleware: GET " << req->url + " -> " << root + decodedPath;
118 } else {
120 << req->url + " -> " << root + decodedPath;
121
122 if (fallThrough) {
123 next();
124 } else {
125 res->status(404).send("Unsupported resource: " + req->url + "\n");
126 }
127 }
128 });
129 });
130 }
131
132 class StaticMiddleware& StaticMiddleware::setIndex(const std::string& index) {
133 this->index = index;
134
135 return *this;
136 }
137
139 this->stdHeaders.clear();
140
141 return *this;
142 }
143
144 class StaticMiddleware& StaticMiddleware::setStdHeaders(const std::map<std::string, std::string>& stdHeaders) {
145 this->stdHeaders = stdHeaders;
146
147 return *this;
148 }
149
150 class StaticMiddleware& StaticMiddleware::appendStdHeaders(const std::map<std::string, std::string>& stdHeaders) {
151 this->stdHeaders.insert(stdHeaders.begin(), stdHeaders.end());
152
153 return *this;
154 }
155
156 class StaticMiddleware& StaticMiddleware::appendStdHeaders(const std::string& field, const std::string& value) {
157 this->stdHeaders[field] = value;
158
159 return *this;
160 }
161
162 class StaticMiddleware& StaticMiddleware::appendStdCookie(const std::string& name,
163 const std::string& value,
164 const std::map<std::string, std::string>& options) {
165 this->stdCookies.insert({name, web::http::CookieOptions(value, options)});
166
167 return *this;
168 }
169
171 this->defaultConnectionState = connectionState;
172
173 return *this;
174 }
175
176 class StaticMiddleware& StaticMiddleware::instance(const std::string& root, bool fallThrough) {
177 // Keep all created static middlewares alive
178 static std::map<const std::string, std::shared_ptr<class StaticMiddleware>> staticMiddlewares;
179
180 if (!staticMiddlewares.contains(root)) {
181 staticMiddlewares[root] = std::shared_ptr<StaticMiddleware>(new StaticMiddleware(root, fallThrough));
182 }
183
184 return *staticMiddlewares[root];
185 }
186
187 // "Constructor" of StaticMiddleware
188 class StaticMiddleware& StaticMiddleware(const std::string& root, bool fallThrough) {
189 return StaticMiddleware::instance(root, fallThrough);
190 }
191
192} // namespace express::middleware
#define LOG(level)
Definition Logger.h:148
#define PLOG(level)
Definition Logger.h:152
#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:98
std::string originalPath
Definition Request.h:78
std::string method
Definition Request.h:97
std::string path
Definition Request.h:79
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
std::map< std::string, web::http::CookieOptions > stdCookies
StaticMiddleware & setIndex(const std::string &index)
StaticMiddleware & appendStdHeaders(const std::string &field, const std::string &value)
web::http::ConnectionState defaultConnectionState
std::map< std::string, std::string > stdHeaders
StaticMiddleware(const std::string &root, bool fallThrough)
static class StaticMiddleware & instance(const std::string &root, bool fallThrough)
StaticMiddleware & afterResponse(web::http::ConnectionState connectionState)
LogMessage(Level level, int verboseLevel=-1, bool withErrno=false)
Definition Logger.cpp:280
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
std::string url_decode(const std::string &text)