Skip to content

Commit 91d433d

Browse files
committed
Allow iteration over headers
1 parent 484739b commit 91d433d

3 files changed

Lines changed: 47 additions & 1 deletion

File tree

‎examples/Headers.js‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/* Example of looping over all headers (not recommended as production solution,
2+
* do NOT use this to "solve" your problems with headers, use ONLY for debugging) */
3+
4+
const uWS = require('../dist/uws.js');
5+
const port = 9001;
6+
7+
const app = uWS./*SSL*/App({
8+
key_file_name: 'misc/key.pem',
9+
cert_file_name: 'misc/cert.pem',
10+
passphrase: '1234'
11+
}).get('/*', (res, req) => {
12+
13+
res.write('<h2>Hello, your headers are:</h2><ul>');
14+
15+
req.forEach((k, v) => {
16+
res.write('<li>');
17+
res.write(k);
18+
res.write(' = ');
19+
res.write(v);
20+
res.write('</li>');
21+
});
22+
23+
res.end('</ul>');
24+
25+
}).listen(port, (token) => {
26+
if (token) {
27+
console.log('Listening to port ' + port);
28+
} else {
29+
console.log('Failed to listen to port ' + port);
30+
}
31+
});

‎src/HttpRequestWrapper.h‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,20 @@ struct HttpRequestWrapper {
1616
return req;
1717
}
1818

19+
/* Takes function of string, string. Returns this (doesn't really but should) */
20+
static void req_forEach(const FunctionCallbackInfo<Value> &args) {
21+
auto *req = getHttpRequest(args);
22+
if (req) {
23+
Local<Function> cb = Local<Function>::Cast(args[0]);
24+
25+
for (auto p : *req) {
26+
Local<Value> argv[] = {String::NewFromUtf8(isolate, p.first.data(), String::kNormalString, p.first.length()),
27+
String::NewFromUtf8(isolate, p.second.data(), String::kNormalString, p.second.length())};
28+
cb->Call(isolate->GetCurrentContext()->Global(), 2, argv);
29+
}
30+
}
31+
}
32+
1933
/* Takes int, returns string (must be in bounds) */
2034
static void req_getParameter(const FunctionCallbackInfo<Value> &args) {
2135
auto *req = getHttpRequest(args);
@@ -83,6 +97,7 @@ struct HttpRequestWrapper {
8397
reqTemplateLocal->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "getUrl"), FunctionTemplate::New(isolate, req_getUrl));
8498
reqTemplateLocal->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "getMethod"), FunctionTemplate::New(isolate, req_getMethod));
8599
reqTemplateLocal->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "getQuery"), FunctionTemplate::New(isolate, req_getQuery));
100+
reqTemplateLocal->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "forEach"), FunctionTemplate::New(isolate, req_forEach));
86101

87102
/* Create the template */
88103
Local<Object> reqObjectLocal = reqTemplateLocal->GetFunction()->NewInstance(isolate->GetCurrentContext()).ToLocalChecked();

‎uWebSockets‎

0 commit comments

Comments
 (0)