Exemplo n.º 1
0
        public Func <HttpListenerRequest, string> FindHandler(HttpListenerRequest request)
        {
            Func <HttpListenerRequest, string> res = null;

            var requestMethod = request.GetHttpMethod();
            var registrator   = registrators.FirstOrDefault(r => r.HttpMethod == requestMethod);

            if (registrator != null)
            {
                res = registrator.Handlers
                      .Where(kv => kv.Key == request.Url.AbsolutePath)
                      .Select(kv => kv.Value)
                      .FirstOrDefault();
            }

            if (res == null && requestMethod == HttpMethod.Get)
            {
                string staticMatch = servedStatic.Keys.FirstOrDefault(k => request.Url.AbsolutePath.StartsWith(k));
                if (staticMatch != null)
                {
                    string fileRelPath = request.Url.AbsolutePath.Substring(staticMatch.Length);
                    if (fileRelPath == "" || fileRelPath == "index")
                    {
                        fileRelPath = "index.html";
                    }
                    string fileAbsPath = Path.Combine(servedStatic[staticMatch].FullName, fileRelPath);
                    if (File.Exists(fileAbsPath))
                    {
                        res = _ => File.ReadAllText(fileAbsPath);
                    }
                }
            }

            return(res);
        }