public void AddHandler(PathHandlerItem phi) { if (GetHandler(phi.Path) != null) { Debug.WriteLine(String.Format("Warning, already has handler for path: {0}", phi.Path)); } Handlers.Add(phi); }
public void On(String Path, WebHandler handler) { Regex reg = null; try { reg = new Regex(Path); } catch (Exception e) { Debug.WriteLine(String.Format("Warning, is not a Regex: {0}\r\n{1}", Path, e)); } PathHandlerItem phi = new PathHandlerItem() { Path = Path, PathReg = reg, Handler = handler }; AddHandler(phi); }
virtual public Response HandleRequest(Client.Request Req) { Response Res = new Response() { Header = new ResponseHeader() { Code = 200, Status = "OK", Protocol = Req.Header.Protocol } }; Res.Header["Server"] = "WPServer"; Res.Header["Content-Type"] = "text/html"; Context cxt = new Context() { Request = Req, Response = Res }; PathHandlerItem phi = GetHandler(Req.Header.Path); if (phi != null) { if (phi.PathReg != null) { cxt.PathArgs = new List <string>(); Match m = phi.PathReg.Match(Req.Path); if (m.Success) { foreach (Group g in m.Groups) { cxt.PathArgs.Add(g.Value); } } } try { System.Reflection.MethodInfo mi = phi.Handler.GetType().GetMethod(Req.Method); if (mi != null) { mi.Invoke(phi.Handler, new object[] { cxt }); } else if (phi.Handler.handler != null) { // phi.Handler.handler(cxt); } else { throw new Exception(String.Format("No handler for {0} {1}", Req.Method, Req.Path)); } } catch (Exception e) { Res.ResponseError(500, "Server Error", String.Format("<html><header><title>Server Error</title></header><body><pre>{0}</pre></body></html>", e.Message + "\r\n" + e.StackTrace)); } } else { Res.ResponseError(404, "Not Found"); } return(cxt.Response); }