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/c/system/main.h"
8 #include "mojo/public/cpp/application/application_delegate.h"
9 #include "mojo/public/cpp/application/application_impl.h"
10 #include "mojo/public/cpp/application/application_runner.h"
11 #include "mojo/public/cpp/utility/run_loop.h"
12 #include "mojo/services/public/interfaces/network/network_service.mojom.h"
13 #include "mojo/services/public/interfaces/network/url_loader.mojom.h"
19 class ResponsePrinter {
21 void Run(URLResponsePtr response) const {
22 if (response->error) {
23 printf("Got error: %d (%s)\n",
24 response->error->code, response->error->description.get().c_str());
26 PrintResponse(response);
27 PrintResponseBody(response->body.Pass());
30 RunLoop::current()->Quit(); // All done!
33 void PrintResponse(const URLResponsePtr& response) const {
34 printf(">>> Headers <<< \n");
35 printf(" %s\n", response->status_line.get().c_str());
36 if (response->headers) {
37 for (size_t i = 0; i < response->headers.size(); ++i)
38 printf(" %s\n", response->headers[i].get().c_str());
42 void PrintResponseBody(ScopedDataPipeConsumerHandle body) const {
43 // Read response body in blocking fashion.
44 printf(">>> Body <<<\n");
48 uint32_t num_bytes = sizeof(buf);
49 MojoResult result = ReadDataRaw(body.get(), buf, &num_bytes,
50 MOJO_READ_DATA_FLAG_NONE);
51 if (result == MOJO_RESULT_SHOULD_WAIT) {
53 MOJO_HANDLE_SIGNAL_READABLE,
54 MOJO_DEADLINE_INDEFINITE);
55 } else if (result == MOJO_RESULT_OK) {
56 if (fwrite(buf, num_bytes, 1, stdout) != 1) {
57 printf("\nUnexpected error writing to file\n");
65 printf("\n>>> EOF <<<\n");
71 class WGetApp : public ApplicationDelegate {
73 virtual void Initialize(ApplicationImpl* app) MOJO_OVERRIDE {
74 app->ConnectToService("mojo:mojo_network_service", &network_service_);
80 std::string url = PromptForURL();
81 printf("Loading: %s\n", url.c_str());
83 network_service_->CreateURLLoader(Get(&url_loader_));
85 URLRequestPtr request(URLRequest::New());
87 request->method = "GET";
88 request->auto_follow_redirects = true;
90 url_loader_->Start(request.Pass(), ResponsePrinter());
93 std::string PromptForURL() {
94 printf("Enter URL> ");
96 if (scanf("%1023s", buf) != 1)
101 NetworkServicePtr network_service_;
102 URLLoaderPtr url_loader_;
105 } // namespace examples
108 MojoResult MojoMain(MojoHandle shell_handle) {
109 mojo::ApplicationRunner runner(new mojo::examples::WGetApp);
110 return runner.Run(shell_handle);