void HandleRequest(RequestContext context) { RegisterRoutes(); try { bool handled = false; for (; context.currentRoute < registeredRoutes.Count; ++context.currentRoute) { RouteAttribute route = registeredRoutes[context.currentRoute]; Match match = route.m_route.Match(context.path); if (!match.Success) { continue; } if (!route.m_methods.IsMatch(context.Request.HttpMethod)) { continue; } // Upgrade to main thread if necessary if (route.m_runOnMainThread && Thread.CurrentThread != mainThread) { lock (mainRequests) { mainRequests.Enqueue(context); } return; } context.match = match; route.m_callback(context); handled = !context.pass; if (handled) { break; } } if (!handled) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; context.Response.StatusDescription = "Not Found"; } } catch (Exception exception) { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.StatusDescription = string.Format("Fatal error:\n{0}", exception); Debug.LogException(exception); } context.Response.OutputStream.Close(); }
static void RegisterFileHandlers() { string pattern = string.Format("({0})", string.Join("|", fileTypes.Select(x => x.Key).ToArray())); RouteAttribute downloadRoute = new RouteAttribute(string.Format(@"^/download/(.*\.{0})$", pattern)); RouteAttribute fileRoute = new RouteAttribute(string.Format(@"^/(.*\.{0})$", pattern)); bool needs_www = fileRoot.Contains("://"); downloadRoute.m_runOnMainThread = needs_www; fileRoute.m_runOnMainThread = needs_www; FileHandlerDelegate callback = FileHandler; if (needs_www) { callback = WWWFileHandler; } downloadRoute.m_callback = delegate(RequestContext context) { callback(context, true); }; fileRoute.m_callback = delegate(RequestContext context) { callback(context, false); }; registeredRoutes.Add(downloadRoute); registeredRoutes.Add(fileRoute); }