📄 process.cc.svn-base
字号:
// 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) { // Extract the C++ request object from the JavaScript wrapper. HttpRequest* request = UnwrapRequest(info.Holder()); // Fetch the path. const string& path = request->Path(); // Wrap the result in a JavaScript string and return it. return String::New(path.c_str(), path.length());}Handle<Value> JsHttpRequestProcessor::GetReferrer(Local<String> name, const AccessorInfo& info) { HttpRequest* request = UnwrapRequest(info.Holder()); const string& path = request->Referrer(); return String::New(path.c_str(), path.length());}Handle<Value> JsHttpRequestProcessor::GetHost(Local<String> name, const AccessorInfo& info) { HttpRequest* request = UnwrapRequest(info.Holder()); const string& path = request->Host(); return String::New(path.c_str(), path.length());}Handle<Value> JsHttpRequestProcessor::GetUserAgent(Local<String> name, const AccessorInfo& info) { HttpRequest* request = UnwrapRequest(info.Holder()); const string& path = request->UserAgent(); return String::New(path.c_str(), path.length());}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("referrer"), GetReferrer); result->SetAccessor(String::NewSymbol("host"), GetHost); result->SetAccessor(String::NewSymbol("userAgent"), GetUserAgent); // 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);}/** * A simplified http request. */class StringHttpRequest : public HttpRequest { public: StringHttpRequest(const string& path, const string& referrer, const string& host, const string& user_agent); virtual const string& Path() { return path_; } virtual const string& Referrer() { return referrer_; } virtual const string& Host() { return host_; } virtual const string& UserAgent() { return user_agent_; } private: string path_; string referrer_; string host_; string user_agent_;};StringHttpRequest::StringHttpRequest(const string& path, const string& referrer, const string& host, const string& user_agent) : path_(path), referrer_(referrer), host_(host), user_agent_(user_agent) { }void ParseOptions(int argc, char* argv[], map<string, string>& options, string* file) { for (int i = 1; i < argc; i++) { string arg = argv[i]; int index = arg.find('=', 0); if (index == string::npos) { *file = arg; } else { string key = arg.substr(0, index); string value = arg.substr(index+1); options[key] = value; } }}// Reads a file into a v8 string.Handle<String> ReadFile(const string& name) { FILE* file = fopen(name.c_str(), "rb"); if (file == NULL) return Handle<String>(); fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { int read = fread(&chars[i], 1, size - i, file); i += read; } fclose(file); Handle<String> result = String::New(chars, size); delete[] chars; return result;}const int kSampleSize = 6;StringHttpRequest kSampleRequests[kSampleSize] = { StringHttpRequest("/process.cc", "localhost", "google.com", "firefox"), StringHttpRequest("/", "localhost", "google.net", "firefox"), StringHttpRequest("/", "localhost", "google.org", "safari"), StringHttpRequest("/", "localhost", "yahoo.com", "ie"), StringHttpRequest("/", "localhost", "yahoo.com", "safari"), StringHttpRequest("/", "localhost", "yahoo.com", "firefox")};bool ProcessEntries(HttpRequestProcessor* processor, int count, StringHttpRequest* reqs) { for (int i = 0; i < count; i++) { if (!processor->Process(&reqs[i])) return false; } return true;}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()); }}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);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -