Allow iteration over headers

This commit is contained in:
Alex Hultman 2019-03-10 12:45:43 +01:00
parent 484739be98
commit 91d433d191
3 changed files with 47 additions and 1 deletions

31
examples/Headers.js Normal file
View File

@ -0,0 +1,31 @@
/* Example of looping over all headers (not recommended as production solution,
* do NOT use this to "solve" your problems with headers, use ONLY for debugging) */
const uWS = require('../dist/uws.js');
const port = 9001;
const app = uWS./*SSL*/App({
key_file_name: 'misc/key.pem',
cert_file_name: 'misc/cert.pem',
passphrase: '1234'
}).get('/*', (res, req) => {
res.write('<h2>Hello, your headers are:</h2><ul>');
req.forEach((k, v) => {
res.write('<li>');
res.write(k);
res.write(' = ');
res.write(v);
res.write('</li>');
});
res.end('</ul>');
}).listen(port, (token) => {
if (token) {
console.log('Listening to port ' + port);
} else {
console.log('Failed to listen to port ' + port);
}
});

View File

@ -16,6 +16,20 @@ struct HttpRequestWrapper {
return req;
}
/* Takes function of string, string. Returns this (doesn't really but should) */
static void req_forEach(const FunctionCallbackInfo<Value> &args) {
auto *req = getHttpRequest(args);
if (req) {
Local<Function> cb = Local<Function>::Cast(args[0]);
for (auto p : *req) {
Local<Value> argv[] = {String::NewFromUtf8(isolate, p.first.data(), String::kNormalString, p.first.length()),
String::NewFromUtf8(isolate, p.second.data(), String::kNormalString, p.second.length())};
cb->Call(isolate->GetCurrentContext()->Global(), 2, argv);
}
}
}
/* Takes int, returns string (must be in bounds) */
static void req_getParameter(const FunctionCallbackInfo<Value> &args) {
auto *req = getHttpRequest(args);
@ -83,6 +97,7 @@ struct HttpRequestWrapper {
reqTemplateLocal->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "getUrl"), FunctionTemplate::New(isolate, req_getUrl));
reqTemplateLocal->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "getMethod"), FunctionTemplate::New(isolate, req_getMethod));
reqTemplateLocal->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "getQuery"), FunctionTemplate::New(isolate, req_getQuery));
reqTemplateLocal->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "forEach"), FunctionTemplate::New(isolate, req_forEach));
/* Create the template */
Local<Object> reqObjectLocal = reqTemplateLocal->GetFunction()->NewInstance(isolate->GetCurrentContext()).ToLocalChecked();

@ -1 +1 @@
Subproject commit cd899fb988bf9bb4306b60acbf6b713b065b7d8c
Subproject commit 0212ee5bd04a0320a3422a5acafe29730e264f57