1 module hunt.http.routing.RouterManager;
2 
3 import hunt.http.routing.handler;
4 import hunt.http.routing.Matcher;
5 import hunt.http.routing.Router;
6 import hunt.http.routing.impl.RouterManagerImpl;
7 
8 import hunt.http.server.HttpRequestOptions;
9 import hunt.http.server.HttpServerContext;
10 
11 import hunt.collection;
12 import hunt.Exceptions;
13 import hunt.util.Common;
14 
15 /**
16  * 
17  */
18 enum RouteGroupType {
19     Default,
20     Host,
21     Path
22 }
23 
24 enum DEFAULT_LAST_ROUTER_ID = int.max / 2;
25 
26 /**
27  * 
28  */
29 interface RouterManager {
30 
31     Router register();
32 
33     Router register(int id);
34 
35     NavigableSet!(RouterMatchResult) findRouter(string method, string path,
36             string contentType, string accept);
37 
38     void accept(HttpServerContext context);
39 
40     // static RouterManager create() {
41     //     return create(new HttpRequestOptions());
42     // }
43 
44     static RouterManager create() {
45         RouterManagerImpl routerManager = new RouterManagerImpl();
46 
47         routerManager.register().path("*").handler(new DefaultRouteHandler());
48 
49         Router currentRouter = routerManager.register(DEFAULT_LAST_ROUTER_ID);
50         currentRouter.path("*")
51             .handler(ErrorResponseHandler.Default());
52         
53         version(HUNT_HTTP_DEBUG) {
54             import hunt.logging;
55             tracef("routeid: %d, paths: *", currentRouter.getId());
56         }
57         
58         return routerManager;
59     }
60 }
61 
62 /**
63  * 
64  */
65 class RouterMatchResult : Comparable!RouterMatchResult {
66 
67     private Router router;
68     private Map!(string, string) parameters;
69     private Set!(Matcher.MatchType) matchTypes;
70 
71     this(Router router, Map!(string, string) parameters, Set!(Matcher.MatchType) matchTypes) {
72         this.router = router;
73         this.parameters = parameters;
74         this.matchTypes = matchTypes;
75     }
76 
77     Router getRouter() {
78         return router;
79     }
80 
81     Map!(string, string) getParameters() {
82         return parameters;
83     }
84 
85     Set!(Matcher.MatchType) getMatchTypes() {
86         return matchTypes;
87     }
88 
89     override int opCmp(Object o) {
90         RouterMatchResult r = cast(RouterMatchResult) o;
91         if (o is null)
92             throw new NullPointerException();
93         return opCmp(r);
94     }
95 
96     int opCmp(RouterMatchResult o) {
97         return router.opCmp(o.getRouter());
98     }
99 
100     override bool opEquals(Object o) {
101         if (this is o)
102             return true;
103         if (o is null || typeid(this) != typeid(o))
104             return false;
105         RouterMatchResult that = cast(RouterMatchResult) o;
106         return router == that.router;
107     }
108 
109     override size_t toHash() @trusted nothrow {
110         return hashOf(router);
111     }
112 }