예제 #1
0
        protected override void HandleRequest(HttpListenerContext context)
        {
            var path  = context.Request.Url.AbsolutePath;
            var parts = path.Split('/');

            if (parts.Length == 1)
            {
                context.Ok();
                return;
            }

            switch (parts[1])
            {
            case ("favicon.ico"):
                context.Ok();
                break;

            case ("Shutdown"):
                context.Ok();
                Shutdown();
                break;

            case ("Produce"):
                HandleProduceRequest(parts, context);
                break;

            default:
                context.Error("Route does not exist");
                break;
            }
        }
예제 #2
0
        private static bool HandleArticleRequest(HttpListenerContext client, int categoryIndex)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                var r        = client.Request;
                var segments = r.Url.Segments;

                if (r.HttpMethod == "GET")
                {
                    if (segments.Length == 2)
                    {
                        GetSummary(client, categoryIndex);
                    }
                    else if (r.QueryString["comments"] != null)
                    {
                        GetComments(client, categoryIndex);
                    }
                    else
                    {
                        GetArticle(client, categoryIndex);
                    }
                }
                else if (r.HttpMethod == "POST")
                {
                    AddComment(client, categoryIndex);
                }
                else
                {
                    client.Error(HttpStatusCode.BadRequest);
                }
            });
            return(true);
        }
예제 #3
0
        public void Execute(HttpListenerContext context)
        {
            var request = context.Request;
            var rawUrl  = request.RawUrl.Contains("?") ? request.RawUrl.Split("?".ToCharArray())[0] : request.RawUrl;

            if (dictionary.ContainsKey(rawUrl))
            {
                try
                {
                    var method      = dictionary[rawUrl];
                    var firstParams = method.GetParameters().FirstOrDefault();

                    if (firstParams.ParameterType == typeof(HttpListenerContext))
                    {
                        var callback    = new ExecuteContextCallback(ExecuteContextAsync);
                        var beginInvoke = callback.BeginInvoke(method, context, this, null, null);

                        callback.EndInvoke(beginInvoke);
                    }
                    else if (typeof(HttpParam).IsAssignableFrom(firstParams.ParameterType))
                    {
                        var Configuration = AutofacUnitwork.Instance.GetServer <FastControllerConfiguration>();

                        if (Configuration.Methods.Any(item => item.Equals(request.HttpMethod, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            var paramContext = Activator.CreateInstance(firstParams.ParameterType, new object[] {
                                context
                            }) as HttpParam;

                            var callback    = new ExecuteHttpCallback(ExecuteHttpAsync);
                            var beginInvoke = callback.BeginInvoke(method, paramContext, this, null, null);

                            callback.EndInvoke(beginInvoke);
                        }
                    }
                    else
                    {
                        context.Error("Not impl param");
                    }
                }
                catch (Exception ex)
                {
                    context.Error(ex.InnerException.Message);
                }
            }
        }
예제 #4
0
        private static bool ValidateProduceRequest(string[] parts, HttpListenerContext context)
        {
            if (parts.Length != 4)
            {
                context.Error("format is /Produce/{exchangeName}/{count}");
                return(false);
            }

            return(true);
        }
예제 #5
0
        private static bool ValidateConsumeRequest(string[] parts, HttpListenerContext context)
        {
            if (parts.Length != 3)
            {
                context.Error("No exchange specified");
                return(false);
            }

            return(true);
        }
예제 #6
0
 private static bool RedirectClient(HttpListenerContext context)
 {
     ThreadPool.QueueUserWorkItem(delegate
     {
         var url = context.Request.Url.Segments;
         if (url.Length < 3)
         {
             context.Error(HttpStatusCode.BadRequest);
             return;
         }
         var key = context.Request.Url.Segments[2];
         if (!Urls.ContainsKey(key))
         {
             context.Error(HttpStatusCode.BadRequest);
             return;
         }
         context.SetHeader("Location", Urls[key]);
         context.Response.StatusCode = (int)HttpStatusCode.Found;
         context.Response.Close();
     });
     return(true);
 }
예제 #7
0
        private void HandleConsumeStop(string[] parts, HttpListenerContext context)
        {
            if (!ValidateConsumeRequest(parts, context))
            {
                return;
            }

            var      exchange = parts[2];
            Consumer consumer;

            if (_consumers.TryGetValue(exchange, out consumer))
            {
                consumer.Dispose();
                _consumers.Remove(exchange);
                context.Ok();
                return;
            }

            context.Error($"No consumer for exchange {exchange} was found");
        }
예제 #8
0
        public void Start(int port)
        {
            var httpListener = new HttpListener();

            httpListener.Prefixes.Add($"http://+:{port}/");
            httpListener.Start();

            while (_process)
            {
                HttpListenerContext context = null;
                try
                {
                    context = httpListener.GetContext();
                    HandleRequest(context);
                }
                catch (Exception e)
                {
                    context?.Error(e.Message);
                }
            }

            HandleShutdown();
        }
예제 #9
0
                #pragma warning restore 0649

        private static void AddComment(HttpListenerContext client, int categoryIndex)
        {
            var r = client.Request;

            string name = null, email = null, text = null;
            int    replyTo = -1;
            var    buf     = new byte[r.ContentLength64];
            var    query   = Encoding.UTF8.GetString(buf, 0, r.InputStream.Read(buf, 0, buf.Length));
            var    param   = query.Split('&');

            foreach (var p in param)
            {
                var segments = p.Split(new[] { '=' }, 2);
                if (segments.Length < 2)
                {
                    client.Error(HttpStatusCode.BadRequest);
                    return;
                }
                var value = Uri.UnescapeDataString(segments[1]).Replace('+', ' ');
                if (segments[0] == "name")
                {
                    name = value;
                }
                else if (segments[0] == "email")
                {
                    email = value;
                }
                else if (segments[0] == "comment")
                {
                    text = value;
                }
                else if (segments[0] == "replyTo")
                {
                    replyTo = int.Parse(segments[1]);
                }
            }
            if (name == null || text == null)
            {
                client.Error(HttpStatusCode.BadRequest);
                return;
            }

            var article = articles[categoryIndex][r.Url.Segments[2]];
            var comment = new Comment(name, text, article.CommentCount, replyTo);

            if (!Validate(comment, article))
            {
                client.Error(HttpStatusCode.BadRequest);
                return;
            }
            article.AddComment(comment);

            if (client.Request.Url.Query.Contains("returnSelf"))
            {
                client.WriteAndClose(GenerateCommentHtml(comment, ""), "html", HttpStatusCode.Created);
            }
            else
            {
                // This should prevent accidently submitting a form multiple times
                client.SetHeader("Location", client.Request.Url);
                client.Close(HttpStatusCode.SeeOther);
            }
        }
예제 #10
0
                #pragma warning restore 0649

        private static void GetArticle(HttpListenerContext client, int categoryIndex)
        {
            var req = client.Request;
            var url = req.Url.Segments;

            if (url.Length < 3)
            {
                client.Error(HttpStatusCode.BadRequest);
                return;
            }
            if (url[url.Length - 1].Contains("."))
            {
                client.GetFile();
                return;
            }
            if (!articles[categoryIndex].ContainsKey(url[2]))
            {
                client.Error(HttpStatusCode.NotFound);
                return;
            }
            var article = articles[categoryIndex][url[2]];
            var path    = ChickenSoup.RootFolder + article.Path;

            if (File.Exists(path))
            {
                var content  = File.ReadAllText(path);
                var comments = article.GetComments();
                var tree     = new CommentTree();
                foreach (var comment in comments)
                {
                    if (!tree.Add(comment))
                    {
                        throw new FormatException($"Comment file of {article.Name} has an invalid comment: {comment}");
                    }
                }
                var response = ArticleTemplate.Replace("{title}", article.Title)
                               .Replace("{time}", article.Date.ToString())
                               .Replace("{time(O)}", article.Date.ToString("O"));
                Action <Article, string, string> replaceLinks = (otherArticle, replace, conditional) =>
                {
                    if (otherArticle != null)
                    {
                        response = response.Replace(replace, otherArticle.Url);
                        response.Replace(replace, "");
                        response.Replace(conditional, "");
                    }
                    else
                    {
                        var s = response.IndexOf(conditional, StringComparison.InvariantCulture);
                        if (s < 0)
                        {
                            return;
                        }
                        var e = response.IndexOf(")}", s + conditional.Length, StringComparison.InvariantCulture) + 2;
                        response = response.Remove(s, e - s);
                    }
                };
                replaceLinks(article.Next, "{next}", "{next??(");
                replaceLinks(article.Previous, "{previous}", "{previous??(");
                response = response.Replace("{content}", File.ReadAllText(path))
                           .Replace("{comments}", GenerateCommentHtml(tree));
                client.WriteAndClose(response, "html", HttpStatusCode.OK);
            }
            else
            {
                client.Error(HttpStatusCode.NotFound);
            }
        }