& headers // if completely empty, content-type: text/html will be added
)
{
//cout << "url [" << url << "]" << endl;
if ( url.size() > 1 ){
handleRESTRequest( rq , url , responseMsg , responseCode , headers );
return;
}
responseCode = 200;
stringstream ss;
ss << "";
string dbname;
{
stringstream z;
z << "db " << getHostName() << ':' << port << ' ';
dbname = z.str();
}
ss << dbname << "" << dbname << "
\n
";
doUnlockedStuff(ss);
int n = 2000;
Timer t;
while ( 1 ) {
if ( !dbMutexInfo.isLocked() ) {
{
dblock lk;
ss << "time to get dblock: " << t.millis() << "ms\n";
doLockedStuff(ss);
}
break;
}
sleepmillis(1);
if ( --n < 0 ) {
ss << "\ntimed out getting dblock\n";
break;
}
}
ss << "";
responseMsg = ss.str();
}
void handleRESTRequest( const char *rq, // the full request
string url,
string& responseMsg,
int& responseCode,
vector& headers // if completely empty, content-type: text/html will be added
){
string::size_type first = url.find( "/" , 1 );
if ( first == string::npos ){
responseCode = 400;
return;
}
string method = parseMethod( rq );
string dbname = url.substr( 1 , first - 1 );
string coll = url.substr( first + 1 );
string action = "";
map params;
if ( coll.find( "?" ) != string::npos ){
parseParams( params , coll.substr( coll.find( "?" ) + 1 ) );
coll = coll.substr( 0 , coll.find( "?" ) );
}
string::size_type last = coll.find_last_of( "/" );
if ( last == string::npos ){
action = coll;
coll = "_defaultCollection";
}
else {
action = coll.substr( last + 1 );
coll = coll.substr( 0 , last );
}
for ( string::size_type i=0; i & params , int & responseCode , stringstream & out ){
static DBDirectClient db;
int skip = _getOption( params["skip"] , 0 );
int num = _getOption( params["count" ] , 0 );
int one = 0;
if ( params["one"].size() > 0 && tolower( params["one"][0] ) == 't' ){
num = 1;
one = 1;
}
BSONObjBuilder query;
auto_ptr cursor = db.query( ns.c_str() , query.doneAndDecouple() , num , skip );
if ( one ){
if ( cursor->more() ){
BSONObj obj = cursor->next();
out << obj.jsonString() << "\n";
}
else {
responseCode = 404;
}
return;
}
out << "{\n";
//ss << " \"total_rows\" : 0 ,\n";
out << " \"offset\" : " << skip << ",\n";
out << " \"rows\": [\n";
int first = 1;
while ( cursor->more() ){
if ( first )
first = 0;
else
out << " ,\n";
BSONObj obj = cursor->next();
out << " " << obj.jsonString();
}
out << "\n ]\n\n";
out << "}\n";
}
int _getOption( string val , int def ){
if ( val.size() == 0 )
return def;
return atoi( val.c_str() );
}
};
void webServerThread() {
boost::thread thr(statsThread);
DbWebServer mini;
if ( mini.init(port+1000) )
mini.run();
}