bool yarp::os::impl::HttpCarrier::write(Protocol& proto, SizedWriter& writer) { DummyConnector con; con.setTextMode(true); for (size_t i=writer.headerLength(); i<writer.length(); i++) { con.getWriter().appendBlock(writer.data(i),writer.length(i)); } Bottle b; b.read(con.getReader()); ConstString body = b.find("web").toString(); if (body.length()!=0) { ConstString header; header += NetType::toHexString(body.length()).c_str(); header += "\r\n"; Bytes b2((char*)header.c_str(),header.length()); proto.os().write(b2); Bytes b3((char*)body.c_str(),body.length()); proto.os().write(b3); proto.os().write('\r'); proto.os().write('\n'); } else { ConstString txt = b.toString() + "\r\n"; ConstString header; header += NetType::toHexString(txt.length()).c_str(); header += "\r\n"; Bytes b2((char*)header.c_str(),header.length()); proto.os().write(b2); Bytes b3((char*)txt.c_str(),txt.length()); proto.os().write(b3); proto.os().write('\r'); proto.os().write('\n'); } proto.os().flush(); return proto.os().isOk(); }
bool yarp::os::impl::HttpCarrier::reply(Protocol& proto, SizedWriter& writer) { DummyConnector con; con.setTextMode(true); for (size_t i=writer.headerLength(); i<writer.length(); i++) { con.getWriter().appendBlock(writer.data(i),writer.length(i)); } Bottle b; b.read(con.getReader()); ConstString mime = b.check("mime",Value("text/html")).asString(); ConstString body; bool using_json = false; if (stream!=NULL) { if (stream->useJson()) { mime = "text/json"; asJson(body,&b,stream->typeHint()); using_json = true; } } if (b.check("web")&&!using_json) { body = b.find("web").toString(); } if (b.check("stream")&&!using_json) { String header("HTTP/1.1 200 OK\r\nContent-Type: "); header += mime; header += "\r\n"; header += "Transfer-Encoding: chunked\r\n"; header += "\r\n"; int N = 2*1024; header += NetType::toHexString(body.length()+N); header += "\r\n"; Bytes b2((char*)header.c_str(),header.length()); proto.os().write(b2); // chrome etc won't render until enough chars are received. for (int i=0; i<N; i++) { proto.os().write(' '); } Bytes b3((char*)body.c_str(),body.length()); proto.os().write(b3); proto.os().write('\r'); proto.os().write('\n'); if (stream!=NULL) { stream->flip(); } return true; } if (stream!=NULL) { stream->finish(); } // Could check response codes, mime types here. if (body.length()!=0 || using_json) { ConstString mime = b.check("mime",Value("text/html")).asString(); String header("HTTP/1.1 200 OK\nContent-Type: "); header += mime; header += "\n"; header += "Access-Control-Allow-Origin: *\n"; header += "\n"; Bytes b2((char*)header.c_str(),header.length()); proto.os().write(b2); //body = b.toString(); Bytes b3((char*)body.c_str(),body.length()); proto.os().write(b3); } else { writer.write(proto.os()); } proto.os().flush(); return proto.os().isOk(); }