1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "mojo/public/cpp/application/application_delegate.h"
8 #include "mojo/public/cpp/application/application_impl.h"
9 #include "mojo/public/cpp/utility/run_loop.h"
10 #include "mojo/services/public/interfaces/network/network_service.mojom.h"
11 #include "mojo/services/public/interfaces/network/url_loader.mojom.h"
17 class ResponsePrinter {
19 void Run(URLResponsePtr response) const {
20 if (response->error) {
21 printf("Got error: %d (%s)\n",
22 response->error->code, response->error->description.get().c_str());
24 PrintResponse(response);
25 PrintResponseBody(response->body.Pass());
28 RunLoop::current()->Quit(); // All done!
31 void PrintResponse(const URLResponsePtr& response) const {
32 printf(">>> Headers <<< \n");
33 printf(" %s\n", response->status_line.get().c_str());
34 if (response->headers) {
35 for (size_t i = 0; i < response->headers.size(); ++i)
36 printf(" %s\n", response->headers[i].get().c_str());
40 void PrintResponseBody(ScopedDataPipeConsumerHandle body) const {
41 // Read response body in blocking fashion.
42 printf(">>> Body <<<\n");
46 uint32_t num_bytes = sizeof(buf);
47 MojoResult result = ReadDataRaw(body.get(), buf, &num_bytes,
48 MOJO_READ_DATA_FLAG_NONE);
49 if (result == MOJO_RESULT_SHOULD_WAIT) {
51 MOJO_HANDLE_SIGNAL_READABLE,
52 MOJO_DEADLINE_INDEFINITE);
53 } else if (result == MOJO_RESULT_OK) {
54 if (fwrite(buf, num_bytes, 1, stdout) != 1) {
55 printf("\nUnexpected error writing to file\n");
63 printf("\n>>> EOF <<<\n");
69 class WGetApp : public ApplicationDelegate {
71 virtual void Initialize(ApplicationImpl* app) MOJO_OVERRIDE {
72 app->ConnectToService("mojo:mojo_network_service", &network_service_);
78 std::string url = PromptForURL();
79 printf("Loading: %s\n", url.c_str());
81 network_service_->CreateURLLoader(Get(&url_loader_));
83 URLRequestPtr request(URLRequest::New());
85 request->method = "GET";
86 request->auto_follow_redirects = true;
88 url_loader_->Start(request.Pass(), ResponsePrinter());
91 std::string PromptForURL() {
92 printf("Enter URL> ");
94 if (scanf("%1023s", buf) != 1)
99 NetworkServicePtr network_service_;
100 URLLoaderPtr url_loader_;
103 } // namespace examples
106 ApplicationDelegate* ApplicationDelegate::Create() {
107 return new examples::WGetApp();