1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "request_dispatcher.h"
18 
19 #include "bar_handler.h"
20 #include "foo_handler.h"
21 
22 #include <iostream>
23 
24 using namespace std;
25 using namespace fruit;
26 
27 class RequestDispatcherImpl : public RequestDispatcher {
28 private:
29   const Request& request;
30   // We hold providers here for lazy injection; we only want to inject the handler that is actually used for the
31   // request.
32   // In a large system, there will be many handlers, and many will have lots of dependencies that also have to be
33   // injected.
34   Provider<FooHandler> fooHandler;
35   Provider<BarHandler> barHandler;
36 
37 public:
INJECT(RequestDispatcherImpl (const Request & request,Provider<FooHandler> fooHandler,Provider<BarHandler> barHandler))38   INJECT(RequestDispatcherImpl(const Request& request, Provider<FooHandler> fooHandler,
39                                Provider<BarHandler> barHandler))
40       : request(request), fooHandler(fooHandler), barHandler(barHandler) {}
41 
handleRequest()42   void handleRequest() override {
43     if (stringStartsWith(request.path, "/foo/")) {
44       fooHandler.get()->handleRequest();
45     } else if (stringStartsWith(request.path, "/bar/")) {
46       barHandler.get()->handleRequest();
47     } else {
48       cerr << "Error: no handler found for request path: '" << request.path << "' , ignoring request." << endl;
49     }
50   }
51 
52 private:
stringStartsWith(const string & s,const string & candidatePrefix)53   static bool stringStartsWith(const string& s, const string& candidatePrefix) {
54     return s.compare(0, candidatePrefix.size(), candidatePrefix) == 0;
55   }
56 };
57 
getRequestDispatcherComponent()58 Component<Required<Request, ServerContext>, RequestDispatcher> getRequestDispatcherComponent() {
59   return createComponent()
60       .bind<RequestDispatcher, RequestDispatcherImpl>()
61       .install(getFooHandlerComponent)
62       .install(getBarHandlerComponent);
63 }
64