mirror of
https://github.com/nodejs/node.git
synced 2026-10-28 10:15:07 +08:00
compactify the code into a single file. will abstract later.
This commit is contained in:
1 parent
90ea571602
commit
d945ba68a2
6 files changed
+249
-673
No files matched your search
@@ -10,15 +10,12 @@ ifdef EVDIR
|
||||
LDFLAGS += -L$(EVDIR)/lib
|
||||
endif
|
||||
|
||||
server: js_http_request_processor.o server.o oi_socket.o ebb_request_parser.o oi_buf.o
|
||||
server: server.o oi_socket.o ebb_request_parser.o oi_buf.o
|
||||
g++ -o server $^ $(LDFLAGS) $(V8LIB)
|
||||
|
||||
server.o: server.cc
|
||||
g++ $(CFLAGS) -c $<
|
||||
|
||||
js_http_request_processor.o: js_http_request_processor.cc
|
||||
g++ $(CFLAGS) -c $<
|
||||
|
||||
ebb_request_parser.o: ebb_request_parser.c deps/ebb/ebb_request_parser.h
|
||||
g++ $(CFLAGS) -c $<
|
||||
|
||||
|
||||
+2
-1
@@ -7,6 +7,7 @@ function Process(request) {
|
||||
}
|
||||
|
||||
request.respond("HTTP/1.0 200 OK\r\n")
|
||||
request.respond("Content-Type: text-plain\r\nContent-Length: 6\r\n\r\nhello\n");
|
||||
request.respond("Content-Type: text-plain\r\n")
|
||||
request.respond("Content-Length: 6\r\n\r\nhello\n");
|
||||
request.respond(null); // eof
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
#ifndef http_request_h
|
||||
#define http_request_h
|
||||
extern "C" {
|
||||
#include <oi_socket.h>
|
||||
#include <ebb_request_parser.h>
|
||||
}
|
||||
#include <string>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Connection {
|
||||
public:
|
||||
Connection ( void)
|
||||
{
|
||||
oi_socket_init (&socket, 30.0);
|
||||
ebb_request_parser_init (&parser);
|
||||
}
|
||||
ebb_request_parser parser;
|
||||
oi_socket socket;
|
||||
};
|
||||
|
||||
class HttpRequest {
|
||||
public:
|
||||
HttpRequest (Connection &c) : connection(c)
|
||||
{
|
||||
ebb_request_init(&parser_info);
|
||||
}
|
||||
~HttpRequest() { }
|
||||
|
||||
string path;
|
||||
|
||||
Connection &connection;
|
||||
ebb_request parser_info;
|
||||
};
|
||||
|
||||
#endif // http_request_h
|
||||
@@ -1,516 +0,0 @@
|
||||
// Copyright 2008 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#include <v8.h>
|
||||
|
||||
// To avoid warnings from <map> on windows we disable exceptions.
|
||||
#define _HAS_EXCEPTIONS 0
|
||||
#include <string>
|
||||
#include <map>
|
||||
|
||||
#include "js_http_request_processor.h"
|
||||
#include <oi_buf.h>
|
||||
|
||||
using namespace std;
|
||||
using namespace v8;
|
||||
|
||||
static Handle<Value> LogCallback
|
||||
( const Arguments& args
|
||||
)
|
||||
{
|
||||
if (args.Length() < 1) return v8::Undefined();
|
||||
HandleScope scope;
|
||||
Handle<Value> arg = args[0];
|
||||
String::Utf8Value value(arg);
|
||||
HttpRequestProcessor::Log(*value);
|
||||
return v8::Undefined();
|
||||
}
|
||||
|
||||
|
||||
// Execute the script and fetch the Process method.
|
||||
bool JsHttpRequestProcessor::Initialize
|
||||
( map<string, string>* opts
|
||||
, map<string, string>* output
|
||||
)
|
||||
{
|
||||
// Create a handle scope to hold the temporary references.
|
||||
HandleScope handle_scope;
|
||||
|
||||
// Create a template for the global object where we set the
|
||||
// built-in global functions.
|
||||
Handle<ObjectTemplate> global = ObjectTemplate::New();
|
||||
global->Set(String::New("log"), FunctionTemplate::New(LogCallback));
|
||||
|
||||
// Each processor gets its own context so different processors
|
||||
// don't affect each other (ignore the first three lines).
|
||||
Handle<Context> context = Context::New(NULL, global);
|
||||
|
||||
// Store the context in the processor object in a persistent handle,
|
||||
// since we want the reference to remain after we return from this
|
||||
// method.
|
||||
context_ = Persistent<Context>::New(context);
|
||||
|
||||
// Enter the new context so all the following operations take place
|
||||
// within it.
|
||||
Context::Scope context_scope(context);
|
||||
|
||||
// Make the options mapping available within the context
|
||||
if (!InstallMaps(opts, output))
|
||||
return false;
|
||||
|
||||
// Compile and run the script
|
||||
if (!ExecuteScript(script_))
|
||||
return false;
|
||||
|
||||
// The script compiled and ran correctly. Now we fetch out the
|
||||
// Process function from the global object.
|
||||
Handle<String> process_name = String::New("Process");
|
||||
Handle<Value> process_val = context->Global()->Get(process_name);
|
||||
|
||||
// If there is no Process function, or if it is not a function,
|
||||
// bail out
|
||||
if (!process_val->IsFunction()) return false;
|
||||
|
||||
// It is a function; cast it to a Function
|
||||
Handle<Function> process_fun = Handle<Function>::Cast(process_val);
|
||||
|
||||
// Store the function in a Persistent handle, since we also want
|
||||
// that to remain after this call returns
|
||||
process_ = Persistent<Function>::New(process_fun);
|
||||
|
||||
// All done; all went well
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool JsHttpRequestProcessor::ExecuteScript
|
||||
( Handle<String> script
|
||||
)
|
||||
{
|
||||
HandleScope handle_scope;
|
||||
|
||||
// We're just about to compile the script; set up an error handler to
|
||||
// catch any exceptions the script might throw.
|
||||
TryCatch try_catch;
|
||||
|
||||
// Compile the script and check for errors.
|
||||
Handle<Script> compiled_script = Script::Compile(script);
|
||||
if (compiled_script.IsEmpty()) {
|
||||
String::Utf8Value error(try_catch.Exception());
|
||||
Log(*error);
|
||||
// The script failed to compile; bail out.
|
||||
return false;
|
||||
}
|
||||
|
||||
// Run the script!
|
||||
Handle<Value> result = compiled_script->Run();
|
||||
if (result.IsEmpty()) {
|
||||
// The TryCatch above is still in effect and will have caught the error.
|
||||
String::Utf8Value error(try_catch.Exception());
|
||||
Log(*error);
|
||||
// Running the script failed; bail out.
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool JsHttpRequestProcessor::InstallMaps
|
||||
( map<string, string>* opts
|
||||
, map<string, string>* output
|
||||
)
|
||||
{
|
||||
HandleScope handle_scope;
|
||||
|
||||
// Wrap the map object in a JavaScript wrapper
|
||||
Handle<Object> opts_obj = WrapMap(opts);
|
||||
|
||||
// Set the options object as a property on the global object.
|
||||
context_->Global()->Set(String::New("options"), opts_obj);
|
||||
|
||||
Handle<Object> output_obj = WrapMap(output);
|
||||
context_->Global()->Set(String::New("output"), output_obj);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool JsHttpRequestProcessor::Process
|
||||
( HttpRequest* request
|
||||
)
|
||||
{
|
||||
// Create a handle scope to keep the temporary object references.
|
||||
HandleScope handle_scope;
|
||||
|
||||
// Enter this processor's context so all the remaining operations
|
||||
// take place there
|
||||
Context::Scope context_scope(context_);
|
||||
|
||||
// Wrap the C++ request object in a JavaScript wrapper
|
||||
Handle<Object> request_obj = WrapRequest(request);
|
||||
|
||||
// Set up an exception handler before calling the Process function
|
||||
TryCatch try_catch;
|
||||
|
||||
// Invoke the process function, giving the global object as 'this'
|
||||
// and one argument, the request.
|
||||
const int argc = 1;
|
||||
Handle<Value> argv[argc] = { request_obj };
|
||||
Handle<Value> result = process_->Call(context_->Global(), argc, argv);
|
||||
if (result.IsEmpty()) {
|
||||
String::Utf8Value error(try_catch.Exception());
|
||||
Log(*error);
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
JsHttpRequestProcessor::~JsHttpRequestProcessor
|
||||
(
|
||||
)
|
||||
{
|
||||
// Dispose the persistent handles. When noone else has any
|
||||
// references to the objects stored in the handles they will be
|
||||
// automatically reclaimed.
|
||||
context_.Dispose();
|
||||
process_.Dispose();
|
||||
}
|
||||
|
||||
|
||||
Persistent<ObjectTemplate> JsHttpRequestProcessor::request_template_;
|
||||
Persistent<ObjectTemplate> JsHttpRequestProcessor::map_template_;
|
||||
|
||||
|
||||
// -----------------------------------
|
||||
// --- A c c e s s i n g M a p s ---
|
||||
// -----------------------------------
|
||||
|
||||
// Utility function that wraps a C++ http request object in a
|
||||
// JavaScript object.
|
||||
Handle<Object> JsHttpRequestProcessor::WrapMap
|
||||
( map<string, string>* obj
|
||||
)
|
||||
{
|
||||
// Handle scope for temporary handles.
|
||||
HandleScope handle_scope;
|
||||
|
||||
// Fetch the template for creating JavaScript map wrappers.
|
||||
// It only has to be created once, which we do on demand.
|
||||
if (request_template_.IsEmpty()) {
|
||||
Handle<ObjectTemplate> raw_template = MakeMapTemplate();
|
||||
map_template_ = Persistent<ObjectTemplate>::New(raw_template);
|
||||
}
|
||||
Handle<ObjectTemplate> templ = map_template_;
|
||||
|
||||
// Create an empty map wrapper.
|
||||
Handle<Object> result = templ->NewInstance();
|
||||
|
||||
// Wrap the raw C++ pointer in an External so it can be referenced
|
||||
// from within JavaScript.
|
||||
Handle<External> map_ptr = External::New(obj);
|
||||
|
||||
// Store the map pointer in the JavaScript wrapper.
|
||||
result->SetInternalField(0, map_ptr);
|
||||
|
||||
// Return the result through the current handle scope. Since each
|
||||
// of these handles will go away when the handle scope is deleted
|
||||
// we need to call Close to let one, the result, escape into the
|
||||
// outer handle scope.
|
||||
return handle_scope.Close(result);
|
||||
}
|
||||
|
||||
|
||||
// Utility function that extracts the C++ map pointer from a wrapper
|
||||
// object.
|
||||
map<string, string>* JsHttpRequestProcessor::UnwrapMap
|
||||
( Handle<Object> obj
|
||||
)
|
||||
{
|
||||
Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0));
|
||||
void* ptr = field->Value();
|
||||
return static_cast<map<string, string>*>(ptr);
|
||||
}
|
||||
|
||||
|
||||
// Convert a JavaScript string to a std::string. To not bother too
|
||||
// much with string encodings we just use ascii.
|
||||
string ObjectToString
|
||||
( Local<Value> value
|
||||
)
|
||||
{
|
||||
String::Utf8Value utf8_value(value);
|
||||
return string(*utf8_value);
|
||||
}
|
||||
|
||||
|
||||
Handle<Value> JsHttpRequestProcessor::MapGet
|
||||
( Local<String> name
|
||||
, const AccessorInfo& info
|
||||
)
|
||||
{
|
||||
// Fetch the map wrapped by this object.
|
||||
map<string, string>* obj = UnwrapMap(info.Holder());
|
||||
|
||||
// Convert the JavaScript string to a std::string.
|
||||
string key = ObjectToString(name);
|
||||
|
||||
// Look up the value if it exists using the standard STL ideom.
|
||||
map<string, string>::iterator iter = obj->find(key);
|
||||
|
||||
// If the key is not present return an empty handle as signal
|
||||
if (iter == obj->end()) return Handle<Value>();
|
||||
|
||||
// Otherwise fetch the value and wrap it in a JavaScript string
|
||||
const string& value = (*iter).second;
|
||||
return String::New(value.c_str(), value.length());
|
||||
}
|
||||
|
||||
|
||||
Handle<Value> JsHttpRequestProcessor::MapSet
|
||||
( Local<String> name
|
||||
, Local<Value> value_obj
|
||||
, const AccessorInfo& info
|
||||
)
|
||||
{
|
||||
// Fetch the map wrapped by this object.
|
||||
map<string, string>* obj = UnwrapMap(info.Holder());
|
||||
|
||||
// Convert the key and value to std::strings.
|
||||
string key = ObjectToString(name);
|
||||
string value = ObjectToString(value_obj);
|
||||
|
||||
// Update the map.
|
||||
(*obj)[key] = value;
|
||||
|
||||
// Return the value; any non-empty handle will work.
|
||||
return value_obj;
|
||||
}
|
||||
|
||||
|
||||
Handle<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate
|
||||
(
|
||||
)
|
||||
{
|
||||
HandleScope handle_scope;
|
||||
|
||||
Handle<ObjectTemplate> result = ObjectTemplate::New();
|
||||
result->SetInternalFieldCount(1);
|
||||
result->SetNamedPropertyHandler(MapGet, MapSet);
|
||||
|
||||
// Again, return the result through the current handle scope.
|
||||
return handle_scope.Close(result);
|
||||
}
|
||||
|
||||
|
||||
// -------------------------------------------
|
||||
// --- A c c e s s i n g R e q u e s t s ---
|
||||
// -------------------------------------------
|
||||
|
||||
/**
|
||||
* Utility function that wraps a C++ http request object in a
|
||||
* JavaScript object.
|
||||
*/
|
||||
Handle<Object> JsHttpRequestProcessor::WrapRequest
|
||||
( HttpRequest* request
|
||||
)
|
||||
{
|
||||
// Handle scope for temporary handles.
|
||||
HandleScope handle_scope;
|
||||
|
||||
// Fetch the template for creating JavaScript http request wrappers.
|
||||
// It only has to be created once, which we do on demand.
|
||||
if (request_template_.IsEmpty()) {
|
||||
Handle<ObjectTemplate> raw_template = MakeRequestTemplate();
|
||||
request_template_ = Persistent<ObjectTemplate>::New(raw_template);
|
||||
}
|
||||
Handle<ObjectTemplate> templ = request_template_;
|
||||
|
||||
// Create an empty http request wrapper.
|
||||
Handle<Object> result = templ->NewInstance();
|
||||
|
||||
// Wrap the raw C++ pointer in an External so it can be referenced
|
||||
// from within JavaScript.
|
||||
Handle<External> request_ptr = External::New(request);
|
||||
|
||||
// Store the request pointer in the JavaScript wrapper.
|
||||
result->SetInternalField(0, request_ptr);
|
||||
|
||||
// Return the result through the current handle scope. Since each
|
||||
// of these handles will go away when the handle scope is deleted
|
||||
// we need to call Close to let one, the result, escape into the
|
||||
// outer handle scope.
|
||||
return handle_scope.Close(result);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Utility function that extracts the C++ http request object from a
|
||||
* wrapper object.
|
||||
*/
|
||||
HttpRequest* JsHttpRequestProcessor::UnwrapRequest
|
||||
( Handle<Object> obj
|
||||
)
|
||||
{
|
||||
Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0));
|
||||
void* ptr = field->Value();
|
||||
return static_cast<HttpRequest*>(ptr);
|
||||
}
|
||||
|
||||
Handle<Value> JsHttpRequestProcessor::GetPath
|
||||
( Local<String> name
|
||||
, const AccessorInfo& info
|
||||
)
|
||||
{
|
||||
HttpRequest* request = UnwrapRequest(info.Holder());
|
||||
return String::New(request->path.c_str(), request->path.length());
|
||||
}
|
||||
|
||||
Handle<Value> JsHttpRequestProcessor::GetMethod
|
||||
( Local<String> name
|
||||
, const AccessorInfo& info
|
||||
)
|
||||
{
|
||||
HttpRequest* request = UnwrapRequest(info.Holder());
|
||||
// TODO allocate these strings only once. reference global
|
||||
switch(request->parser_info.method) {
|
||||
case EBB_COPY: return String::New("COPY");
|
||||
case EBB_DELETE: return String::New("DELETE");
|
||||
case EBB_GET: return String::New("GET");
|
||||
case EBB_HEAD: return String::New("HEAD");
|
||||
case EBB_LOCK: return String::New("LOCK");
|
||||
case EBB_MKCOL: return String::New("MKCOL");
|
||||
case EBB_MOVE: return String::New("MOVE");
|
||||
case EBB_OPTIONS: return String::New("OPTIONS");
|
||||
case EBB_POST: return String::New("POST");
|
||||
case EBB_PROPFIND: return String::New("PROPFIND");
|
||||
case EBB_PROPPATCH: return String::New("PROPPATCH");
|
||||
case EBB_PUT: return String::New("PUT");
|
||||
case EBB_TRACE: return String::New("TRACE");
|
||||
case EBB_UNLOCK: return String::New("UNLOCK");
|
||||
default:
|
||||
return Null();
|
||||
}
|
||||
}
|
||||
|
||||
Handle<Value> JsHttpRequestProcessor::RespondCallback
|
||||
( const Arguments& args
|
||||
)
|
||||
{
|
||||
HttpRequest* request = UnwrapRequest(args.Holder());
|
||||
if (args.Length() < 1) return v8::Undefined();
|
||||
HandleScope scope;
|
||||
Handle<Value> arg = args[0];
|
||||
|
||||
// TODO Make sure that we write reponses in the correct order. With
|
||||
// keep-alive it's possible that one response can return before the last
|
||||
// one has been sent!!!
|
||||
|
||||
if(arg == Null()) {
|
||||
|
||||
request->connection.socket.on_drain = oi_socket_close;
|
||||
|
||||
} else {
|
||||
|
||||
Local<String> s = arg->ToString();
|
||||
|
||||
oi_buf *buf = oi_buf_new2(s->Length());
|
||||
s->WriteAscii(buf->base);
|
||||
|
||||
oi_socket_write(&request->connection.socket, buf);
|
||||
|
||||
}
|
||||
|
||||
return v8::Undefined();
|
||||
}
|
||||
|
||||
|
||||
Handle<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate
|
||||
(
|
||||
)
|
||||
{
|
||||
HandleScope handle_scope;
|
||||
|
||||
Handle<ObjectTemplate> result = ObjectTemplate::New();
|
||||
result->SetInternalFieldCount(1);
|
||||
|
||||
// Add accessors for each of the fields of the request.
|
||||
result->SetAccessor(String::NewSymbol("path"), GetPath);
|
||||
result->SetAccessor(String::NewSymbol("method"), GetMethod);
|
||||
result->Set(String::New("respond"), FunctionTemplate::New(RespondCallback));
|
||||
|
||||
// Again, return the result through the current handle scope.
|
||||
return handle_scope.Close(result);
|
||||
}
|
||||
|
||||
|
||||
// --- Test ---
|
||||
|
||||
|
||||
void HttpRequestProcessor::Log
|
||||
( const char* event
|
||||
)
|
||||
{
|
||||
printf("Logged: %s\n", event);
|
||||
}
|
||||
|
||||
void PrintMap
|
||||
( map<string, string>* m
|
||||
)
|
||||
{
|
||||
for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) {
|
||||
pair<string, string> entry = *i;
|
||||
printf("%s: %s\n", entry.first.c_str(), entry.second.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
#if 0
|
||||
int main(int argc, char* argv[]) {
|
||||
map<string, string> options;
|
||||
string file;
|
||||
ParseOptions(argc, argv, options, &file);
|
||||
if (file.empty()) {
|
||||
fprintf(stderr, "No script was specified.\n");
|
||||
return 1;
|
||||
}
|
||||
HandleScope scope;
|
||||
Handle<String> source = ReadFile(file);
|
||||
if (source.IsEmpty()) {
|
||||
fprintf(stderr, "Error reading '%s'.\n", file.c_str());
|
||||
return 1;
|
||||
}
|
||||
JsHttpRequestProcessor processor(source);
|
||||
map<string, string> output;
|
||||
if (!processor.Initialize(&options, &output)) {
|
||||
fprintf(stderr, "Error initializing processor.\n");
|
||||
return 1;
|
||||
}
|
||||
if (!ProcessEntries(&processor, kSampleSize, kSampleRequests))
|
||||
return 1;
|
||||
PrintMap(&output);
|
||||
}
|
||||
#endif
|
||||
@@ -1,92 +0,0 @@
|
||||
#ifndef js_http_request_processor_h
|
||||
#define js_http_request_processor_h
|
||||
|
||||
#include <v8.h>
|
||||
#include <string>
|
||||
#include <map>
|
||||
|
||||
#include "http_request.h"
|
||||
|
||||
using namespace std;
|
||||
using namespace v8;
|
||||
|
||||
// These interfaces represent an existing request processing interface.
|
||||
// The idea is to imagine a real application that uses these interfaces
|
||||
// and then add scripting capabilities that allow you to interact with
|
||||
// the objects through JavaScript.
|
||||
|
||||
|
||||
/**
|
||||
* The abstract superclass of http request processors.
|
||||
*/
|
||||
class HttpRequestProcessor {
|
||||
public:
|
||||
virtual ~HttpRequestProcessor() { }
|
||||
|
||||
// Initialize this processor. The map contains options that control
|
||||
// how requests should be processed.
|
||||
virtual bool Initialize(map<string, string>* options,
|
||||
map<string, string>* output) = 0;
|
||||
|
||||
// Process a single request.
|
||||
virtual bool Process(HttpRequest* req) = 0;
|
||||
|
||||
static void Log(const char* event);
|
||||
};
|
||||
|
||||
/**
|
||||
* An http request processor that is scriptable using JavaScript.
|
||||
*/
|
||||
class JsHttpRequestProcessor : public HttpRequestProcessor {
|
||||
public:
|
||||
|
||||
// Creates a new processor that processes requests by invoking the
|
||||
// Process function of the JavaScript script given as an argument.
|
||||
explicit JsHttpRequestProcessor(Handle<String> script) : script_(script) { }
|
||||
virtual ~JsHttpRequestProcessor();
|
||||
|
||||
virtual bool Initialize(map<string, string>* opts,
|
||||
map<string, string>* output);
|
||||
virtual bool Process(HttpRequest* req);
|
||||
|
||||
private:
|
||||
|
||||
// Execute the script associated with this processor and extract the
|
||||
// Process function. Returns true if this succeeded, otherwise false.
|
||||
bool ExecuteScript(Handle<String> script);
|
||||
|
||||
// Wrap the options and output map in a JavaScript objects and
|
||||
// install it in the global namespace as 'options' and 'output'.
|
||||
bool InstallMaps(map<string, string>* opts, map<string, string>* output);
|
||||
|
||||
// Constructs the template that describes the JavaScript wrapper
|
||||
// type for requests.
|
||||
static Handle<ObjectTemplate> MakeRequestTemplate();
|
||||
static Handle<ObjectTemplate> MakeMapTemplate();
|
||||
|
||||
// Callbacks that access the individual fields of request objects.
|
||||
static Handle<Value> GetPath (Local<String> name, const AccessorInfo& info);
|
||||
static Handle<Value> GetMethod (Local<String> name, const AccessorInfo& info);
|
||||
static Handle<Value> RespondCallback (const Arguments& args);
|
||||
|
||||
// Callbacks that access maps
|
||||
static Handle<Value> MapGet(Local<String> name, const AccessorInfo& info);
|
||||
static Handle<Value> MapSet(Local<String> name,
|
||||
Local<Value> value,
|
||||
const AccessorInfo& info);
|
||||
|
||||
// Utility methods for wrapping C++ objects as JavaScript objects,
|
||||
// and going back again.
|
||||
static Handle<Object> WrapMap(map<string, string>* obj);
|
||||
static map<string, string>* UnwrapMap(Handle<Object> obj);
|
||||
static Handle<Object> WrapRequest(HttpRequest* obj);
|
||||
static HttpRequest* UnwrapRequest(Handle<Object> obj);
|
||||
|
||||
Handle<String> script_;
|
||||
Persistent<Context> context_;
|
||||
Persistent<Function> process_;
|
||||
static Persistent<ObjectTemplate> request_template_;
|
||||
static Persistent<ObjectTemplate> map_template_;
|
||||
};
|
||||
|
||||
#endif // js_http_request_processor_h
|
||||
@@ -1,10 +1,5 @@
|
||||
extern "C" {
|
||||
#include <oi.h>
|
||||
#include <ebb_request_parser.h>
|
||||
}
|
||||
|
||||
#include "http_request.h"
|
||||
#include "js_http_request_processor.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <assert.h>
|
||||
@@ -17,13 +12,146 @@ using namespace v8;
|
||||
using namespace std;
|
||||
|
||||
#define PORT "1981"
|
||||
#define MAX_URL 500
|
||||
|
||||
static oi_server server;
|
||||
static struct ev_loop *loop;
|
||||
static JsHttpRequestProcessor *processor;
|
||||
|
||||
void on_path
|
||||
static Persistent<Context> context_;
|
||||
static Persistent<Function> process_;
|
||||
static Persistent<ObjectTemplate> request_template_;
|
||||
|
||||
class Connection {
|
||||
public:
|
||||
Connection ( void)
|
||||
{
|
||||
oi_socket_init (&socket, 30.0);
|
||||
ebb_request_parser_init (&parser);
|
||||
}
|
||||
ebb_request_parser parser;
|
||||
oi_socket socket;
|
||||
};
|
||||
|
||||
class HttpRequest {
|
||||
public:
|
||||
HttpRequest (Connection &c);
|
||||
~HttpRequest() { }
|
||||
|
||||
string path;
|
||||
|
||||
Connection &connection;
|
||||
ebb_request parser_info;
|
||||
|
||||
Persistent<Object> js_object;
|
||||
};
|
||||
|
||||
HttpRequest* UnwrapRequest
|
||||
( Handle<Object> obj
|
||||
)
|
||||
{
|
||||
Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0));
|
||||
void* ptr = field->Value();
|
||||
return static_cast<HttpRequest*>(ptr);
|
||||
}
|
||||
|
||||
Handle<Value> GetPath
|
||||
( Local<String> name
|
||||
, const AccessorInfo& info
|
||||
)
|
||||
{
|
||||
HttpRequest* request = UnwrapRequest(info.Holder());
|
||||
return String::New(request->path.c_str(), request->path.length());
|
||||
}
|
||||
|
||||
Handle<Value> GetMethod
|
||||
( Local<String> name
|
||||
, const AccessorInfo& info
|
||||
)
|
||||
{
|
||||
HttpRequest* request = UnwrapRequest(info.Holder());
|
||||
// TODO allocate these strings only once. reference global
|
||||
switch(request->parser_info.method) {
|
||||
case EBB_COPY: return String::New("COPY");
|
||||
case EBB_DELETE: return String::New("DELETE");
|
||||
case EBB_GET: return String::New("GET");
|
||||
case EBB_HEAD: return String::New("HEAD");
|
||||
case EBB_LOCK: return String::New("LOCK");
|
||||
case EBB_MKCOL: return String::New("MKCOL");
|
||||
case EBB_MOVE: return String::New("MOVE");
|
||||
case EBB_OPTIONS: return String::New("OPTIONS");
|
||||
case EBB_POST: return String::New("POST");
|
||||
case EBB_PROPFIND: return String::New("PROPFIND");
|
||||
case EBB_PROPPATCH: return String::New("PROPPATCH");
|
||||
case EBB_PUT: return String::New("PUT");
|
||||
case EBB_TRACE: return String::New("TRACE");
|
||||
case EBB_UNLOCK: return String::New("UNLOCK");
|
||||
default:
|
||||
return Null();
|
||||
}
|
||||
}
|
||||
|
||||
Handle<Value> RespondCallback
|
||||
( const Arguments& args
|
||||
)
|
||||
{
|
||||
HttpRequest* request = UnwrapRequest(args.Holder());
|
||||
HandleScope scope;
|
||||
Handle<Value> arg = args[0];
|
||||
|
||||
// TODO Make sure that we write reponses in the correct order. With
|
||||
// keep-alive it's possible that one response can return before the last
|
||||
// one has been sent!!!
|
||||
|
||||
if(arg == Null()) {
|
||||
|
||||
request->connection.socket.on_drain = oi_socket_close;
|
||||
|
||||
} else {
|
||||
|
||||
Local<String> s = arg->ToString();
|
||||
|
||||
oi_buf *buf = oi_buf_new2(s->Length());
|
||||
s->WriteAscii(buf->base);
|
||||
|
||||
oi_socket_write(&request->connection.socket, buf);
|
||||
|
||||
}
|
||||
|
||||
return Undefined();
|
||||
}
|
||||
|
||||
HttpRequest::HttpRequest (Connection &c) : connection(c)
|
||||
{
|
||||
ebb_request_init(&parser_info);
|
||||
|
||||
HandleScope handle_scope;
|
||||
|
||||
if (request_template_.IsEmpty()) {
|
||||
Handle<ObjectTemplate> raw_template = ObjectTemplate::New();
|
||||
raw_template->SetInternalFieldCount(1);
|
||||
|
||||
// Add accessors for each of the fields of the request.
|
||||
raw_template->SetAccessor(String::NewSymbol("path"), GetPath);
|
||||
raw_template->SetAccessor(String::NewSymbol("method"), GetMethod);
|
||||
raw_template->Set(String::New("respond"), FunctionTemplate::New(RespondCallback));
|
||||
|
||||
request_template_ = Persistent<ObjectTemplate>::New(raw_template);
|
||||
}
|
||||
Handle<ObjectTemplate> templ = request_template_;
|
||||
|
||||
// Create an empty http request wrapper.
|
||||
Handle<Object> result = templ->NewInstance();
|
||||
|
||||
// Wrap the raw C++ pointer in an External so it can be referenced
|
||||
// from within JavaScript.
|
||||
Handle<External> request_ptr = External::New(this);
|
||||
|
||||
// Store the request pointer in the JavaScript wrapper.
|
||||
result->SetInternalField(0, request_ptr);
|
||||
|
||||
js_object = Persistent<Object>::New(result);
|
||||
}
|
||||
|
||||
static void on_path
|
||||
( ebb_request *req
|
||||
, const char *buf
|
||||
, size_t len
|
||||
@@ -33,28 +161,51 @@ void on_path
|
||||
request->path.append(buf, len);
|
||||
}
|
||||
|
||||
void on_headers_complete
|
||||
static void on_headers_complete
|
||||
( ebb_request *req
|
||||
)
|
||||
{
|
||||
HttpRequest *request = static_cast<HttpRequest*> (req->data);
|
||||
|
||||
bool r = processor->Process(request);
|
||||
if(r) {
|
||||
printf("successful request\n");
|
||||
} else {
|
||||
printf("unsuccesful request\n");
|
||||
}
|
||||
// Create a handle scope to keep the temporary object references.
|
||||
HandleScope handle_scope;
|
||||
|
||||
// Enter this processor's context so all the remaining operations
|
||||
// take place there
|
||||
Context::Scope context_scope(context_);
|
||||
|
||||
// Set up an exception handler before calling the Process function
|
||||
TryCatch try_catch;
|
||||
|
||||
// Invoke the process function, giving the global object as 'this'
|
||||
// and one argument, the request.
|
||||
const int argc = 1;
|
||||
Handle<Value> argv[argc] = { request->js_object };
|
||||
Handle<Value> result = process_->Call(context_->Global(), argc, argv);
|
||||
if (result.IsEmpty()) {
|
||||
String::Utf8Value error(try_catch.Exception());
|
||||
printf("error: %s\n", *error);
|
||||
}
|
||||
}
|
||||
|
||||
void on_request_complete
|
||||
static void on_request_complete
|
||||
( ebb_request *req
|
||||
)
|
||||
{
|
||||
HttpRequest *request = static_cast<HttpRequest*> (req->data);
|
||||
}
|
||||
|
||||
static void on_body
|
||||
( ebb_request *req
|
||||
, const char *chunk
|
||||
, size_t length
|
||||
)
|
||||
{
|
||||
HttpRequest *request = static_cast<HttpRequest*> (req->data);
|
||||
|
||||
|
||||
}
|
||||
|
||||
ebb_request * on_request
|
||||
( void *data
|
||||
)
|
||||
@@ -70,7 +221,7 @@ ebb_request * on_request
|
||||
request->parser_info.on_header_field = NULL;
|
||||
request->parser_info.on_header_value = NULL;
|
||||
request->parser_info.on_headers_complete = on_headers_complete;
|
||||
request->parser_info.on_body = NULL;
|
||||
request->parser_info.on_body = on_body;
|
||||
request->parser_info.on_complete = on_request_complete;
|
||||
request->parser_info.data = request;
|
||||
|
||||
@@ -174,6 +325,51 @@ void ParseOptions
|
||||
}
|
||||
}
|
||||
|
||||
bool ExecuteScript
|
||||
( Handle<String> script
|
||||
)
|
||||
{
|
||||
HandleScope handle_scope;
|
||||
|
||||
// We're just about to compile the script; set up an error handler to
|
||||
// catch any exceptions the script might throw.
|
||||
TryCatch try_catch;
|
||||
|
||||
// Compile the script and check for errors.
|
||||
Handle<Script> compiled_script = Script::Compile(script);
|
||||
if (compiled_script.IsEmpty()) {
|
||||
String::Utf8Value error(try_catch.Exception());
|
||||
printf("error: %s\n", *error);
|
||||
// The script failed to compile; bail out.
|
||||
return false;
|
||||
}
|
||||
|
||||
// Run the script!
|
||||
Handle<Value> result = compiled_script->Run();
|
||||
if (result.IsEmpty()) {
|
||||
// The TryCatch above is still in effect and will have caught the error.
|
||||
String::Utf8Value error(try_catch.Exception());
|
||||
printf("error: %s\n", *error);
|
||||
// Running the script failed; bail out.
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static Handle<Value> LogCallback
|
||||
( const Arguments& args
|
||||
)
|
||||
{
|
||||
if (args.Length() < 1) return v8::Undefined();
|
||||
HandleScope scope;
|
||||
Handle<Value> arg = args[0];
|
||||
String::Utf8Value value(arg);
|
||||
|
||||
printf("Logged: %s\n", *value);
|
||||
|
||||
return v8::Undefined();
|
||||
}
|
||||
|
||||
int main
|
||||
( int argc
|
||||
, char *argv[]
|
||||
@@ -193,16 +389,38 @@ int main
|
||||
return 1;
|
||||
}
|
||||
|
||||
processor = new JsHttpRequestProcessor(source);
|
||||
map<string, string> output;
|
||||
if (!processor->Initialize(&options, &output)) {
|
||||
fprintf(stderr, "Error initializing processor.\n");
|
||||
return 1;
|
||||
}
|
||||
Handle<ObjectTemplate> global = ObjectTemplate::New();
|
||||
global->Set(String::New("log"), FunctionTemplate::New(LogCallback));
|
||||
|
||||
Handle<Context> context = Context::New(NULL, global);
|
||||
|
||||
context_ = Persistent<Context>::New(context);
|
||||
|
||||
Context::Scope context_scope(context);
|
||||
|
||||
// Compile and run the script
|
||||
if (!ExecuteScript(source))
|
||||
return false;
|
||||
|
||||
// The script compiled and ran correctly. Now we fetch out the
|
||||
// Process function from the global object.
|
||||
Handle<String> process_name = String::New("Process");
|
||||
Handle<Value> process_val = context->Global()->Get(process_name);
|
||||
|
||||
// If there is no Process function, or if it is not a function,
|
||||
// bail out
|
||||
if (!process_val->IsFunction()) return false;
|
||||
|
||||
// It is a function; cast it to a Function
|
||||
Handle<Function> process_fun = Handle<Function>::Cast(process_val);
|
||||
|
||||
// Store the function in a Persistent handle, since we also want
|
||||
// that to remain after this call returns
|
||||
process_ = Persistent<Function>::New(process_fun);
|
||||
|
||||
/////////////////////////////////////
|
||||
|
||||
/////////////////////////////////////
|
||||
/////////////////////////////////////
|
||||
|
||||
loop = ev_default_loop(0);
|
||||
|
||||
@@ -227,5 +445,9 @@ int main
|
||||
printf("Running at http://localhost:%s/\n", PORT);
|
||||
|
||||
ev_loop(loop, 0);
|
||||
|
||||
context_.Dispose();
|
||||
process_.Dispose();
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user