29 #include "absl/memory/memory.h"
30 #include "absl/strings/numbers.h"
31 #include "absl/strings/str_cat.h"
32 #include "absl/strings/string_view.h"
33 #include "tensorflow_serving/util/net_http/server/public/httpserver.h"
34 #include "tensorflow_serving/util/net_http/server/public/httpserver_interface.h"
35 #include "tensorflow_serving/util/net_http/server/public/server_request_interface.h"
39 using absl::StrAppend;
46 using tensorflow::serving::net_http::SetContentTypeHTML;
48 void EchoHandler(ServerRequestInterface* req) {
54 " <meta charset='utf-8'>\n"
55 " <title>Request Echo HTTP Server</title>\n"
58 " <h1>Print the HTTP request detail</h1>\n"
61 StrAppend(&response,
"HTTP Method: ", req->http_method(),
" <br>\n");
62 StrAppend(&response,
"Request Uri: ", req->uri_path(),
" <br>\n");
64 StrAppend(&response,
"<br><br>====<br><br>\n");
65 for (
auto header : req->request_headers()) {
66 StrAppend(&response, header,
": ", req->GetRequestHeader(header),
"<br>\n");
71 auto request_chunk = req->ReadRequestBytes(&num_bytes);
72 bool print_break =
false;
73 while (request_chunk !=
nullptr) {
75 StrAppend(&response,
"<br><br>====<br><br>\n");
78 StrAppend(&response, absl::string_view(request_chunk.get(),
79 static_cast<size_t>(num_bytes)));
80 request_chunk = req->ReadRequestBytes(&num_bytes);
83 req->WriteResponseString(response);
85 SetContentTypeHTML(req);
90 class MyExcecutor final :
public EventExecutor {
92 MyExcecutor() =
default;
94 void Schedule(std::function<
void()> fn)
override { fn(); }
98 std::unique_ptr<HTTPServerInterface> StartServer(
int port) {
99 auto options = absl::make_unique<ServerOptions>();
100 options->AddPort(port);
101 options->SetExecutor(absl::make_unique<MyExcecutor>());
103 auto server = CreateEvHTTPServer(std::move(options));
105 if (server ==
nullptr) {
109 RequestHandlerOptions handler_options;
110 server->RegisterRequestHandler(
"/print", EchoHandler, handler_options);
113 bool success = server->StartAcceptingRequests();
124 int main(
int argc,
char** argv) {
126 std::cerr <<
"Usage: http-server <port:8080>" << std::endl;
131 bool port_parsed = absl::SimpleAtoi(argv[1], &port);
133 std::cerr <<
"Invalid port: " << argv[1] << std::endl;
136 auto server = StartServer(port);
138 if (server !=
nullptr) {
139 server->WaitForTermination();
142 std::cerr <<
"Failed to start the server." << std::endl;