private static async void HandleRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response, IRequestHandler handler) { _log.DebugFormat("Matched a handler {0}:{1} {2}", handler.Method, handler.Path, DumpQueryParams(handler.QueryParams)); if (handler.ResponseDelay > TimeSpan.Zero) { await Task.Delay(handler.ResponseDelay); } IDataProducer dataProducer = GetDataProducer(request, handler); if (request.HasBody()) { body.Connect(new BufferedConsumer( bufferedBody => { handler.RecordRequest(request, bufferedBody); _log.DebugFormat("Body: {0}", bufferedBody); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); }, error => { _log.DebugFormat("Error while reading body {0}", error.Message); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); } )); } else { response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); handler.RecordRequest(request, null); } _log.DebugFormat("End Processing request for : {0}:{1}", request.Method, request.Uri); }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Look inside the cache for the specified file. Cache c = new Cache(false); string path = HttpUtility.UrlDecode(components.Where((value, row) => row >= 2).Aggregate((a, b) => a + "/" + b)); if (!c.Exists("server/" + appname + "/store/" + path)) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } // Calculate patch path from source to destination. string result = ""; Hash source = Hash.FromString(components[0]); Hash destination = Hash.FromString(components[1]); while (source != destination) { // Find the patch in the patches that will turn source // into the next patch. IEnumerable <string> patches = c.List("server/" + appname + "/patches/" + path).Where(v => v.StartsWith(source.ToString() + "-")); if (patches.Count() != 1) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } string next = patches.First(); source = Hash.FromString(next.Substring((source.ToString() + "-").Length)); using (StreamReader reader = new StreamReader(c.GetFilePath("server/" + appname + "/patches/" + path + "/" + next))) { result += "--- NEXT PATCH (" + reader.BaseStream.Length + ") ---\r\n"; result += reader.ReadToEnd(); result += "\r\n"; } } result += "--- END OF PATCHES ---\r\n"; // Return data. response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", result.Length.ToString() }, { "Connection", "close" } } }, new BufferedProducer(result)); }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Look inside the cache for the specified file. Cache c = new Cache(false); string path = HttpUtility.UrlDecode(components.Where((value, row) => row >= 2).Aggregate((a, b) => a + "/" + b)); if (!c.Exists("server/" + appname + "/store/" + path)) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } // Calculate patch path from source to destination. string result = ""; Hash source = Hash.FromString(components[0]); Hash destination = Hash.FromString(components[1]); while (source != destination) { // Find the patch in the patches that will turn source // into the next patch. IEnumerable<string> patches = c.List("server/" + appname + "/patches/" + path).Where(v => v.StartsWith(source.ToString() + "-")); if (patches.Count() != 1) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } string next = patches.First(); source = Hash.FromString(next.Substring((source.ToString() + "-").Length)); using (StreamReader reader = new StreamReader(c.GetFilePath("server/" + appname + "/patches/" + path + "/" + next))) { result += "--- NEXT PATCH (" + reader.BaseStream.Length + ") ---\r\n"; result += reader.ReadToEnd(); result += "\r\n"; } } result += "--- END OF PATCHES ---\r\n"; // Return data. response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" }, { "Content-Length", result.Length.ToString() }, { "Connection", "close" } } }, new BufferedProducer(result)); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Uri.StartsWith("/feed.xml")) { var body = new FeedBuilder(Port).Generate(FeedTitle, FilePaths, ImagePath); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new SimpleProducer(body)); return; } // deal with request for file content string uri = request.Uri.Replace("%20", " ").Replace("/", "\\"); string filePath = FilePaths.Where(d => d.Contains(uri)).FirstOrDefault(); if (filePath != null) { FileInfo fi = new FileInfo(filePath); string mimeType = GetMimeType(filePath); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", mimeType }, { "Content-Length", fi.Length.ToString() }, } }; response.OnResponse(headers, new FileProducer(filePath)); return; } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new SimpleProducer(responseBody); response.OnResponse(headers, body); return; } }
private static void HandleTouchRequest(string path, IHttpResponseDelegate response) { var comp = path.Split('/').Last(); var uid = uint.Parse(comp); var npid = 0x110000100000000 | uid; var fileID = npid.ToString("x16") + "_mpdata"; var document = new NPFile(); document.Id = fileID; document.SetData(new byte[12288]); CDatabase.Database.CreateDocument(document, new MindTouch.Tasking.Result <NPFile>()).Wait(); var responseText = "Touched."; var responseBytes = Encoding.ASCII.GetBytes(responseText); response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Length", responseBytes.Length.ToString() }, { "Content-Type", "text/plain" } } }, new BufferedProducer(responseBytes)); }
private static HttpRequestHead EchoPost(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" } } }; if (request.Headers.ContainsKey("Content-Length")) { headers.Headers["Content-Length"] = request.Headers["Content-Length"]; } // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); return(request); }
internal static void SerializeResponse(Object o, IHttpResponseDelegate response) { var s = new JavaScriptSerializer(); string json = s.Serialize(o); var headers = GetOkHeaders(json.Length); response.OnResponse(headers, new BufferedProducer(json)); }
private void ProcessGETRequest(IDataProducer body, HttpRequestHead head, IHttpResponseDelegate response) { var qs = head.QueryString.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Split(new char[] { '=' }, StringSplitOptions.None)) .ToDictionary(p => p[0], p => HttpUtility.UrlDecode(p[1])); string[] lines = qs["metrics"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int index = 0; index < lines.Length; index++) { _parent._target.Post(lines[index]); } _parent._systemMetrics.LogCount("listeners.http.lines", lines.Length); _parent._systemMetrics.LogCount("listeners.http.bytes", Encoding.UTF8.GetByteCount(qs["metrics"])); var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "application-xml" }, { "Content-Length", "0" }, { "Access-Control-Allow-Origin", "*" } } }; response.OnResponse(responseHead, new EmptyResponse()); }
private static void TurnOnElement(HttpRequestHead request, IHttpResponseDelegate response) { var status = new Status(); NameValueCollection parms = GetParameters(request); if (!parms.HasKeys() && parms["id"] != null && parms["time"] != null && parms["color"] != null) { HttpResponseHead headers = GetHeaders(0, HttpStatusCode.BadRequest.ToString()); response.OnResponse(headers, new BufferedProducer("")); return; } if (parms["color"].Length != 7 || !parms["color"].StartsWith("#")) { status.Message = "Invalid color. Must be Hex."; SerializeResponse(status, response); return; } Guid elementId = Guid.Empty; bool allElements = false; int seconds; if ("all".Equals(parms["id"])) { allElements = true; } else { Guid.TryParse(parms["id"], out elementId); } if (!int.TryParse(parms["time"], out seconds)) { status.Message = "Time must be numeric."; SerializeResponse(status, response); return; } Color elementColor = ColorTranslator.FromHtml(parms["color"]); //TODO the following logic for all does not properly deal with discrete color elements when turning all on //TODO they will not respond to turning on white if they are set up with a filter. //TODO enhance this to figure out what colors there are and turn them all on when we are turning all elements on. var effect = new SetLevel { TimeSpan = TimeSpan.FromSeconds(seconds), Color = elementColor, IntensityLevel = 1, TargetNodes = allElements ? VixenSystem.Nodes.GetRootNodes().ToArray() : new[] { VixenSystem.Nodes.GetElementNode(elementId) } }; Module.LiveSystemContext.Execute(new EffectNode(effect, TimeSpan.Zero)); status.Message = string.Format("{0} element(s) turned on for {1} seconds at 100% intensity.", allElements?"All":VixenSystem.Nodes.GetElementNode(elementId).Name, seconds); SerializeResponse(status, response); }
private static void TurnOnElement(HttpRequestHead request, IHttpResponseDelegate response) { var status = new Status(); NameValueCollection parms = GetParameters(request); if (!parms.HasKeys() && parms["id"] != null && parms["time"] != null && parms["color"]!=null) { HttpResponseHead headers = GetHeaders(0, HttpStatusCode.BadRequest.ToString()); response.OnResponse(headers, new BufferedProducer("")); return; } if (parms["color"].Length != 7 || !parms["color"].StartsWith("#")) { status.Message = "Invalid color. Must be Hex."; SerializeResponse(status,response); return; } Guid elementId = Guid.Empty; bool allElements = false; int seconds; if ("all".Equals(parms["id"])) { allElements = true; } else { Guid.TryParse(parms["id"], out elementId); } if (!int.TryParse(parms["time"], out seconds)) { status.Message = "Time must be numeric."; SerializeResponse(status,response); return; } Color elementColor = ColorTranslator.FromHtml(parms["color"]); //TODO the following logic for all does not properly deal with discrete color elements when turning all on //TODO they will not respond to turning on white if they are set up with a filter. //TODO enhance this to figure out what colors there are and turn them all on when we are turning all elements on. var effect = new SetLevel { TimeSpan = TimeSpan.FromSeconds(seconds), Color = elementColor, IntensityLevel = 1, TargetNodes = allElements ? VixenSystem.Nodes.GetRootNodes().ToArray() : new[] {VixenSystem.Nodes.GetElementNode(elementId)} }; Module.LiveSystemContext.Execute(new EffectNode(effect, TimeSpan.Zero)); status.Message = string.Format("{0} element(s) turned on for {1} seconds at 100% intensity.", allElements?"All":VixenSystem.Nodes.GetElementNode(elementId).Name, seconds); SerializeResponse(status,response); }
public void OnResponse(HttpResponseHead head, bool hasBody) { if (hasBody) { subject = new SimpleSubject( () => userCode.ConnectResponseBody(this), () => userCode.DisconnectResponseBody(this)); } responseDelegate.OnResponse(head, subject); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var verror = "404 Not Found"; var errorString = "Not Found"; try { var path = request.Uri; if (path == "/api") { var method = request.Method; var stream = new MemoryStream(); if (method == "POST") { requestBody.Connect(new BufferedConsumer(bufferedBody => { var data = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bufferedBody).Split(new[] { "\r\n\r\n" }, 2, StringSplitOptions.RemoveEmptyEntries)[1]); stream.Write(data, 0, data.Length); stream.Position = 0; HandleAPIRequest(stream, method, response); }, error => { Log.Error(error.ToString()); })); } else { HandleAPIRequest(stream, method, response); } return; } } catch (Exception ex) { verror = "500 Internal Server Error"; Log.Error(ex.ToString()); errorString = ex.ToString(); } response.OnResponse(new HttpResponseHead() { Status = verror, Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", errorString.Length.ToString() } } }, new BufferedProducer(errorString)); }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Look inside the cache for the specified file. Cache c = new Cache(false); string path = HttpUtility.UrlDecode(components.Aggregate((a, b) => a + "/" + b)); if (!c.Exists("server/" + appname + "/store/" + path)) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string> { { "Connection", "close" } } }, new StreamReaderProducer(c.GetFilePath("server/" + appname + "/store/" + path))); }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Get a list of all of the files in the store for this application. Cache c = new Cache(false); IEnumerable <string> files = c.ListRecursive("server/" + appname + "/store"); // Create ZIP file and copy files into it. using (ZipFile zip = new ZipFile()) { // Add the files. foreach (string s in files) { ZipEntry e = zip.AddFile(c.GetFilePath("server/" + appname + "/store/" + s), this.GetDirectoryName(s)); e.Comment = "Added by Pivot.Server."; } // Add the README-UPDATES.txt file. zip.AddEntry("README-UPDATES.txt", @"About =============== This ZIP file was automatically generated by the Pivot.Update server. Refer to https://github.com/hach-que/Pivot.Update/ for more information. Usage Notice =============== The software contained in this ZIP file may use Pivot.Update to automatically update itself when new versions are released. In the event that it does, a UAC prompt may appear when the related Windows service first needs to be installed. This Windows service is responsible for automatically updating applications on a periodic basis; without this service, the associated software will not automatially update. "); zip.Comment = "ZIP file automatically generated by Pivot.Server."; using (MemoryStream output = new MemoryStream()) { zip.Save(output); // Send the ZIP file. response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "application/zip" }, { "Content-Length", output.Length.ToString() }, { "Content-Disposition", "attachment; filename=\"" + appname + ".zip\"" }, { "Connection", "close" } } }, new BufferedProducer(output.ToArray())); } } }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Look inside the cache for the specified file. Cache c = new Cache(false); string path = HttpUtility.UrlDecode(components.Aggregate((a, b) => a + "/" + b)); if (!c.Exists("server/" + appname + "/store/" + path)) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Connection", "close" } } }, new StreamReaderProducer(c.GetFilePath("server/" + appname + "/store/" + path))); }
private void PlaySequence(HttpRequestHead request, IHttpResponseDelegate response) { HttpResponseHead headers; var status = new Status(); NameValueCollection parms = GetParameters(request); if (!parms.HasKeys() && parms["name"] != null) { headers = GetHeaders(0, HttpStatusCode.BadRequest.ToString()); response.OnResponse(headers, new BufferedProducer("")); return; } string fileName = HttpUtility.UrlDecode(parms["name"]); if (_context != null && (_context.IsRunning)) { status.Message = string.Format("Already playing {0}", _context.Sequence.Name); } else { ISequence sequence = SequenceService.Instance.Load(fileName); if (sequence == null) { headers = GetOkHeaders(0); headers.Status = HttpStatusCode.NotFound.ToString(); response.OnResponse(headers, new BufferedProducer("")); return; } Logging.Info(string.Format("Web - Prerendering effects for sequence: {0}", sequence.Name)); Parallel.ForEach(sequence.SequenceData.EffectData.Cast <IEffectNode>(), effectNode => effectNode.Effect.PreRender()); _context = VixenSystem.Contexts.CreateSequenceContext(new ContextFeatures(ContextCaching.NoCaching), sequence); _context.ContextEnded += context_ContextEnded; _context.Play(TimeSpan.Zero, sequence.Length); status.Message = string.Format("Playing sequence {0} of length {1}", sequence.Name, sequence.Length); } SerializeResponse(status, response); }
public void OnRequest(HttpRequestHead head, Kayak.IDataProducer body, IHttpResponseDelegate response) { string[] components = head.Uri.Trim('/').Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (components.Length <= 1) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } foreach (IOperation o in this.m_Operations) { if (o.Handles(components[1].ToLowerInvariant())) { o.Handle(components[0], components.Where((value, row) => row >= 2).ToArray(), head, body, response); return; } } // If all else fails.. response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); }
internal static HttpRequestHead UnsupportedOperation(HttpRequestHead request, IHttpResponseDelegate response) { var serializer = new JavaScriptSerializer(); string json = serializer.Serialize(new Status { Message = "Unknown request" }); HttpResponseHead headers = GetOkHeaders(json.Length); headers.Status = HttpStatusCode.BadRequest.ToString(); response.OnResponse(headers, new BufferedProducer(json)); return(request); }
private static void HandleServersRequest(IHttpResponseDelegate response) { var status = "200 OK"; var outputStream = new MemoryStream(); var outputWriter = new StreamWriter(outputStream); try { var templateStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("DWServer.Templates.Servers.cshtml"); var templateReader = new StreamReader(templateStream); var template = templateReader.ReadToEnd(); templateReader.Close(); var sessions = DWMatch.Sessions; outputWriter.Write(Razor.Parse(template, sessions)); outputWriter.Flush(); } catch (RazorEngine.Templating.TemplateCompilationException e) { status = "500 Internal Server Error"; outputWriter.Write("<pre>"); outputWriter.Write(e.ToString()); outputWriter.Write("\n"); foreach (var err in e.Errors) { outputWriter.Write(err.ToString() + "\n"); outputWriter.Write(err.ErrorText + "\n"); } outputWriter.Write(e.SourceCode); outputWriter.Write("</pre>"); outputWriter.Flush(); } response.OnResponse(new HttpResponseHead() { Status = status, Headers = new Dictionary <string, string>() { { "Content-Length", outputStream.Length.ToString() }, { "Content-Type", "text/html" } } }, new BufferedProducer(((MemoryStream)outputStream).GetBuffer())); }
private void ProcessClientAccessPolicyRequest(IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "text/xml" }, { "Content-Length", Encoding.UTF8.GetByteCount(SILVERLIGHT_CROSSDOMAIN).ToString() } } }; response.OnResponse(responseHead, new BufferedProducer(SILVERLIGHT_CROSSDOMAIN)); }
private CatchInfoBase <Task> .CatchResult HandleError(IHttpResponseDelegate response, CatchInfo errorInfo) { Console.Error.WriteLine("Error from Gate application."); Console.Error.WriteStackTrace(errorInfo.Exception); response.OnResponse(new HttpResponseHead() { Status = "503 Internal Server Error", Headers = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase) { { "Connection", "close" } } }, null); return(errorInfo.Handled()); }
private void Respond(IHttpResponseDelegate response, string status) { var responseHead = new HttpResponseHead() { Status = status, Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", "0" }, { "Access-Control-Allow-Origin", "*" } } }; response.OnResponse(responseHead, new EmptyResponse()); }
private static void NotFoundResponse(HttpRequestHead request, IHttpResponseDelegate response) { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary <string, string>() { { "Content-Type", "text/html" }, { "Content-Length", responseBody.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(responseBody)); }
private static void ReturnHttpMockNotFound(IHttpResponseDelegate response) { var dictionary = new Dictionary <string, string> { { HttpHeaderNames.ContentLength, "0" }, { "X-HttpMockError", "No handler found to handle request" } }; var notFoundResponse = new HttpResponseHead { Status = string.Format("{0} {1}", 404, "NotFound"), Headers = dictionary }; response.OnResponse(notFoundResponse, null); }
private void ProcessCrossDomainRequest(IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "application-xml" }, { "Content-Length", Encoding.UTF8.GetByteCount(FLASH_CROSSDOMAIN).ToString() }, { "Access-Control-Allow-Origin", "*" } } }; response.OnResponse(responseHead, new BufferedProducer(FLASH_CROSSDOMAIN)); }
private void ProcessFileNotFound(IDataProducer body, IHttpResponseDelegate response) { _parent._systemMetrics.LogCount("listeners.http.404"); var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", Encoding.UTF8.GetByteCount("not found").ToString() }, { "Access-Control-Allow-Origin", "*" } } }; response.OnResponse(headers, new BufferedProducer("not found")); }
private void ProcessOPTIONSRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", "0" } }) }; response.OnResponse(responseHead, new EmptyResponse()); }
Action<Exception> HandleError(IHttpResponseDelegate response) { return error => { Console.Error.WriteLine("Error from Gate application."); Console.Error.WriteStackTrace(error); response.OnResponse(new HttpResponseHead() { Status = "503 Internal Server Error", Headers = new Dictionary<string, string>() { { "Connection", "close" } } }, null); }; }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var ea = new RequestReceivedEventArgs(); ea.RequestHead = request; ea.ResponseHead = ResponseMessageHelper.GetHttpResponseHead(); string contentType = string.Empty; if (ea.RequestHead.Headers.ContainsKey("Content-Type")) { contentType = ea.RequestHead.Headers["Content-Type"]; } int contentSize = 0; if (ea.RequestHead.Headers.ContainsKey("Content-Length")) { int.TryParse(ea.RequestHead.Headers["Content-Length"], out contentSize); } BufferedConsumer bc = new BufferedConsumer(bodyContents => { try { ea.RequestBody = bodyContents; //Called when request body is read to end if (RequestReceived != null) { RequestReceived(this, ea); } var bp = ea.ResponseBodyProducer as BufferedProducer; if (bp != null) { ea.ResponseHead.Headers["Content-Length"] = bp.GetContentLength().ToString(); } } finally { response.OnResponse(ea.ResponseHead, ea.ResponseBodyProducer); } }, error => { }, contentType, contentSize); //Gets complete HTTP Request and runs code defined over requestBody.Connect(bc); }
private void ProcessOPTIONSRequest(IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", "0" }, { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, OPTIONS" }, { "Access-Control-Allow-Headers", "X-Requested-With,Content-Type" } } }; response.OnResponse(responseHead, new EmptyResponse()); }
private void Respond(HttpRequestHead head, IHttpResponseDelegate response, string status) { var responseHead = new HttpResponseHead() { Status = status, Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", "0" } } ) }; response.OnResponse(responseHead, new EmptyResponse()); }
private static void GetResourceByName(string contentRequest, IHttpResponseDelegate response) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" }, { "Content-Length", "0" }, { "Cache-Control", "max-age=31536000" } } }; BufferedProducer producer = new BufferedProducer(""); if (_assembly == null) { _assembly = Assembly.GetAssembly(typeof(VixenModules.App.WebServer.HTTP.RequestDelegate)); } try { var resources = _assembly.GetManifestResourceNames(); var resourceItem = resources.FirstOrDefault(n => n.EndsWith(contentRequest, StringComparison.CurrentCultureIgnoreCase)); if (resourceItem == null) { throw new ApplicationException(string.Format("Requested Resource {0} does not exist.", contentRequest)); } using (var _Stream = _assembly.GetManifestResourceStream(resourceItem)) { var bytes = ReadFully(_Stream); headers.Headers["Content-Length"] = bytes.Length.ToString(); headers.Headers["Content-Type"] = GetContentType(contentRequest); producer = new BufferedProducer(bytes); } } catch (Exception e) { Logging.ErrorException(e.Message, e); headers.Status = "404 Not Found"; } response.OnResponse(headers, producer); }
private void HandleResponse(IHttpResponseDelegate response, IDictionary <string, object> env) { var headers = (IDictionary <string, string[]>)env[OwinConstants.ResponseHeaders]; if (!headers.ContainsKey("Content-Length") && !headers.ContainsKey("Transfer-Encoding")) { // disable keep-alive in this case headers["Connection"] = new[] { "close" }; } response.OnResponse(new HttpResponseHead() { Status = GetStatus(env), Headers = headers.ToDictionary(kv => kv.Key, kv => string.Join("\r\n", kv.Value.ToArray()), StringComparer.OrdinalIgnoreCase), }, null /* result.Body == null ? null : new DataProducer(result.Body) */); // TODO: How do we expose DataProducer as a Stream? }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Look inside the cache for a list of files. Cache c = new Cache(false); string s = ""; foreach (string key in c.ListRecursive("server/" + appname + "/hashes")) s += c.Get<Hash>("server/" + appname + "/hashes/" + key) + " " + key + "\r\n"; response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" }, { "Content-Length", s.Length.ToString() }, { "Connection", "close" } } }, new BufferedProducer(s)); }
private void ProcessFileNotFound(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { _parent._systemMetrics.LogCount("listeners.http.404"); var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", Encoding.UTF8.GetByteCount("not found").ToString() } } ) }; response.OnResponse(headers, new BufferedProducer("not found")); }
private void ProcessClientAccessPolicyRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var silverlightCrossdomain = _corsValidator.GetSilverlightCrossDomainPolicy(); var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string> { { "Content-Type", "text/xml" }, { "Content-Length", Encoding.UTF8.GetByteCount(silverlightCrossdomain).ToString() } } ) }; response.OnResponse(responseHead, new BufferedProducer(silverlightCrossdomain)); }
private void RequestProcessingCompleted(NancyContext context, IHttpResponseDelegate response) { HttpResponseHead responseHead = new HttpResponseHead { Headers = context.Response.Headers, Status = context.Response.StatusCode.ToString() }; byte[] responseBodyData; using (MemoryStream ms = new MemoryStream()) { context.Response.Contents(ms); //ms.Seek(0, SeekOrigin.Begin); responseBodyData = ms.ToArray(); } responseHead.Headers["Content-Type"] = context.Response.ContentType; responseHead.Headers["Content-Length"] = responseBodyData.LongLength.ToString(); BufferedProducer bodyDataProducer = new BufferedProducer (responseBodyData); response.OnResponse(responseHead, bodyDataProducer); }
public void OnRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response) { _log.DebugFormat("Start Processing request for : {0}:{1}", request.Method, request.Uri); if (GetHandlerCount() < 1) { ReturnHttpMockNotFound(response); return; } RequestHandler handler = MatchHandler(request); if (handler == null) { _log.DebugFormat("No Handlers matched"); ReturnHttpMockNotFound(response); return; } _log.DebugFormat("Matched a handler {0},{1}, {2}", handler.Method, handler.Path, DumpQueryParams(handler.QueryParams)); IDataProducer dataProducer = GetDataProducer(request, handler); if (request.HasBody()) { body.Connect(new BufferedConsumer( bufferedBody => { handler.RecordRequest(request, bufferedBody); _log.DebugFormat("Body: {0}", bufferedBody); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); }, error => { _log.DebugFormat("Error while reading body {0}", error.Message); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); } )); } else { response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); handler.RecordRequest(request, null); } _log.DebugFormat("End Processing request for : {0}:{1}", request.Method, request.Uri); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/bufferedecho")) { // when you subecribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. requestBody.Connect(new BufferedConsumer(bufferedBody => { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; response.OnResponse(headers, new BufferedProducer(bufferedBody)); }, error => { // XXX // uh oh, what happens? })); } else if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/echo")) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" } } }; if (request.Headers.ContainsKey("Content-Length")) headers.Headers["Content-Length"] = request.Headers["Content-Length"]; // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); } else if (request.Uri.StartsWith("/")) { var body = string.Format( "Hello world.\r\nHello.\r\n\r\nUri: {0}\r\nPath: {1}\r\nQuery:{2}\r\nFragment: {3}\r\n", request.Uri, request.Path, request.QueryString, request.Fragment); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
Action<ResultParameters, Exception> HandleResponse(IHttpResponseDelegate response) { return (result, error) => { if (error != null) { HandleError(response).Invoke(error); return; } if (result.Headers == null) { result.Headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); } if (result.Body != null && !result.Headers.ContainsKey("Content-Length") && !result.Headers.ContainsKey("Transfer-Encoding")) { // disable keep-alive in this case result.Headers["Connection"] = new[] { "close" }; } response.OnResponse(new HttpResponseHead() { Status = GetStatus(result), Headers = result.Headers.ToDictionary(kv => kv.Key, kv => string.Join("\r\n", kv.Value.ToArray()), StringComparer.OrdinalIgnoreCase), }, result.Body == null ? null : new DataProducer(result.Body)); }; }
/// <summary> /// IHttpRequestHandler.OnRequest internal handler /// </summary> internal void onRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { RESTMethod method; if (Enum.TryParse<RESTMethod>(head.Method, out method)) { Pair<ResourceInstance, object[]> resourceParameterPair = retrieveResource(head.Path, method); ResourceInstance resource = resourceParameterPair.V1; object[] resourceParameters = resourceParameterPair.V2; if (resource != null) { ResourceMethod resourceMethod = resource.GetResourceMethod(method); if (resourceMethod != null) { if (resourceMethod.Parameters.Length == resourceParameters.Length + 1) { NameValueCollection getQuery = HttpUtility.ParseQueryString(head.QueryString ?? ""); // now, if it's a POST, read POST data then if (method == RESTMethod.POST) { var consumer = new BufferedConsumer(bufferedBody => { HttpMultipartParser.MultipartFormDataParser parser = new HttpMultipartParser.MultipartFormDataParser(new MemoryStream(Encoding.Default.GetBytes(bufferedBody))); NameValueCollection postQuery = new NameValueCollection(); foreach (var param in parser.Parameters) postQuery.Add(param.Key, param.Value.Data); Context invocationContext = new Context(new Request(head, postQuery, getQuery)); giveResponse(resourceMethod, invocationContext, response, resourceParameters); }, error => { _logger.Error("IDataProducer.Connect failed", error); }); body.Connect(consumer); } else { Context invocationContext = new Context(new Request(head, getParameters: getQuery)); giveResponse(resourceMethod, invocationContext, response, resourceParameters); } } else { Response notFoundResponse = Response.Error(HttpStatusCode.NotFound); response.OnResponse(notFoundResponse.Head, notFoundResponse.Body); } } else { Response notImplementedResponse = Response.Error(HttpStatusCode.NotImplemented); response.OnResponse(notImplementedResponse.Head, notImplementedResponse.Body); } } else { Response notFoundResponse = Response.Error(HttpStatusCode.NotFound); response.OnResponse(notFoundResponse.Head, notFoundResponse.Body); } } else { Response methodNotAllowedResponse = Response.Error(HttpStatusCode.MethodNotAllowed); response.OnResponse(methodNotAllowedResponse.Head, methodNotAllowedResponse.Body); } }
private void HandleResponse(IHttpResponseDelegate response, ResultParameters result) { if (result.Headers == null) { result.Headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); } if (result.Body != null && !result.Headers.ContainsKey("Content-Length") && !result.Headers.ContainsKey("Transfer-Encoding")) { // disable keep-alive in this case result.Headers["Connection"] = new[] { "close" }; } response.OnResponse(new HttpResponseHead() { Status = GetStatus(result), Headers = result.Headers.ToDictionary(kv => kv.Key, kv => string.Join("\r\n", kv.Value.ToArray()), StringComparer.OrdinalIgnoreCase), }, null /* result.Body == null ? null : new DataProducer(result.Body) */); // TODO: How do we expose DataProducer as a Stream? }
private void Respond(IHttpResponseDelegate response, string status) { var responseHead = new HttpResponseHead() { Status = status, Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", "0" }, { "Access-Control-Allow-Origin", "*"} } }; response.OnResponse(responseHead, new EmptyResponse()); }
private CatchInfoBase<Task>.CatchResult HandleError(IHttpResponseDelegate response, CatchInfo errorInfo) { Console.Error.WriteLine("Error from Gate application."); Console.Error.WriteStackTrace(errorInfo.Exception); response.OnResponse(new HttpResponseHead() { Status = "503 Internal Server Error", Headers = new Dictionary<string, string>() { { "Connection", "close" } } }, null); return errorInfo.Handled(); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Uri == "/") { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", "20" }, } }; var body = new BufferedProducer("Hello world.\r\nHello."); response.OnResponse(headers, body); } else if (request.Uri == "/bufferedecho") { // when you subecribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. requestBody.Connect(new BufferedConsumer(bufferedBody => { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; response.OnResponse(headers, new BufferedProducer(bufferedBody)); }, error => { // XXX // uh oh, what happens? })); } else if (request.Uri == "/echo") { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
private void ProcessCrossDomainRequest(IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string> { { "Content-Type", "application-xml" }, { "Content-Length", Encoding.UTF8.GetByteCount(FLASH_CROSSDOMAIN).ToString() }, { "Access-Control-Allow-Origin", "*"} } }; response.OnResponse(responseHead, new BufferedProducer(FLASH_CROSSDOMAIN)); }
/// <summary> /// Give response if methodInvocationDelegate set one; if not, give an error response /// </summary> private void giveResponse(ResourceMethod resourceMethod, Context invocationContext, IHttpResponseDelegate response, object[] parameters) { object[] completeParameters = new Object[] { invocationContext }.Concat(parameters).ToArray(); resourceMethod.Method.DynamicInvoke(completeParameters); if (invocationContext.Response != null) response.OnResponse(invocationContext.Response.Head, invocationContext.Response.Body); else { Response conflictResponse = Response.Error(HttpStatusCode.Conflict); response.OnResponse(conflictResponse.Head, conflictResponse.Body); } }
ResultDelegate HandleResponse(IHttpResponseDelegate response) { return (status, headers, body) => { if (headers == null) headers = new Dictionary<string, string>(); if (body != null && !headers.ContainsKey("Content-Length") && !(headers.ContainsKey("Transfer-Encoding") && headers["Transfer-Encoding"] == "chunked")) { // consume body and calculate Content-Length BufferBody(response)(status, headers, body); } else { response.OnResponse(new HttpResponseHead() { Status = status, Headers = headers }, body == null ? null : new DataProducer(body)); } }; }
private void ProcessFileNotFound(IDataProducer body, IHttpResponseDelegate response) { _parent._systemMetrics.LogCount("listeners.http.404"); var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" }, { "Content-Length", Encoding.UTF8.GetByteCount("not found").ToString() }, { "Access-Control-Allow-Origin", "*"} } }; response.OnResponse(headers, new BufferedProducer("not found")); }
private static void ReturnHttpMockNotFound(IHttpResponseDelegate response) { var dictionary = new Dictionary<string, string> { {HttpHeaderNames.ContentLength, "0"}, {"X-HttpMockError", "No handler found to handle request"} }; var notFoundResponse = new HttpResponseHead {Status = string.Format("{0} {1}", 404, "NotFound"), Headers = dictionary}; response.OnResponse(notFoundResponse, null); }
ResultDelegate BufferBody(IHttpResponseDelegate response) { return (status, headers, body) => { var buffer = new LinkedList<ArraySegment<byte>>(); body((data, continuation) => { var copy = new byte[data.Count]; Buffer.BlockCopy(data.Array, data.Offset, copy, 0, data.Count); buffer.AddLast(new ArraySegment<byte>(copy)); return false; }, HandleError(response), () => { var contentLength = buffer.Aggregate(0, (r, i) => r + i.Count); IDataProducer responseBody = null; if (contentLength > 0) { headers["Content-Length"] = contentLength.ToString(); responseBody = new DataProducer((onData, onError, onComplete) => { bool cancelled = false; while (!cancelled && buffer.Count > 0) { var next = buffer.First; buffer.RemoveFirst(); onData(next.Value, null); } onComplete(); buffer = null; return () => cancelled = true; }); } response.OnResponse(new HttpResponseHead() { Status = status, Headers = headers }, responseBody); }); }; }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/next")) { // when you subscribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. bool ret = MainWindow.Next(); var body = ret ? "Successfully skipped." : "You have to wait for 20 seconds to skip again."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/pause")) { MainWindow.Pause(); var body = "Paused."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/play")) { MainWindow.Play(); var body = "Playing."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/toggleplaypause")) { var body = ""; if (MainWindow._player.Playing) { body = "Paused."; } else { body = "Playing."; } MainWindow.PlayPauseToggle(); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/like")) { MainWindow.Like(); var body = "Like"; if (MainWindow.GetCurrentSong().Loved) body = "Liked"; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/dislike")) { MainWindow.Dislike(); var body = "Disliked."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/currentsong")) { Song s = MainWindow.GetCurrentSong(); var body = new JavaScriptSerializer().Serialize(s); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/connect")) { var body = "true"; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Uri.StartsWith("/")) { var body = string.Format( "Hello world.\r\nHello.\r\n\r\nUri: {0}\r\nPath: {1}\r\nQuery:{2}\r\nFragment: {3}\r\n", request.Uri, request.Path, request.QueryString, request.Fragment); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
private void ProcessGETRequest(IDataProducer body, HttpRequestHead head, IHttpResponseDelegate response) { var qs = head.QueryString.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Split(new string[] { "=" }, StringSplitOptions.None)) .ToDictionary(p => p[0], p => HttpUtility.UrlDecode(p[1])); string[] lines = qs["metrics"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); for (int index = 0; index < lines.Length; index++) { _parent._target.Post(lines[index]); } _parent._systemMetrics.LogCount("listeners.http.lines", lines.Length); _parent._systemMetrics.LogCount("listeners.http.bytes", Encoding.UTF8.GetByteCount(qs["metrics"])); var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string> { { "Content-Type", "application-xml" }, { "Content-Length", "0" }, { "Access-Control-Allow-Origin", "*"} } }; response.OnResponse(responseHead, new EmptyResponse()); }
ResultDelegate HandleResponse(IHttpResponseDelegate response) { return (status, headers, body) => { if (headers == null) headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); if (body != null && !headers.ContainsKey("Content-Length") && !headers.ContainsKey("Transfer-Encoding")) { // disable keep-alive in this case headers["Connection"] = new[] {"close"}; } response.OnResponse(new HttpResponseHead() { Status = status, Headers = headers.ToDictionary(kv => kv.Key, kv => string.Join("\r\n", kv.Value.ToArray()), StringComparer.OrdinalIgnoreCase), }, body == null ? null : new DataProducer(body)); }; }
private void ProcessOPTIONSRequest(IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" }, { "Content-Length", "0" }, { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, OPTIONS" }, { "Access-Control-Allow-Headers", "X-Requested-With,Content-Type" } } }; response.OnResponse(responseHead, new EmptyResponse()); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if(request.Uri == "/favicon.ico") return; var actionName = request.Uri.Substring(1); var action = Repository.GetAction(actionName); action.Command.Run(); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", "20" }, } }; IDataProducer body = new BufferedBody("Hello world.\r\nHello."); response.OnResponse(headers, body); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { List<string> commands = new List<string> {"showNotes","SyncDatabase"}; NameValueCollection vars = HttpUtility.ParseQueryString(request.QueryString); string args = ""; if (request.Method.ToUpperInvariant() == "GET" && vars["a"] != null && commands.Contains(vars["a"])) { string res = "error"; args += String.Format("{0} ", vars["a"]); vars.Remove("a"); foreach (string arg in vars.AllKeys) { args += String.Format("/{0} \"{1}\" ", arg, vars[arg]); } try { //create another instance of this process ProcessStartInfo info = new ProcessStartInfo(); info.FileName = String.Format("\"{0}\"",EvernoteLinkServer.gENScriptPath); info.Arguments = args; Process.Start(info); res = String.Format("{0} {1}", info.FileName, info.Arguments); } catch (Exception e) { res = e.Message; } var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", res.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(res)); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
private static void HandleRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response, IRequestHandler handler) { _log.DebugFormat("Matched a handler {0}:{1} {2}", handler.Method, handler.Path, DumpQueryParams(handler.QueryParams)); IDataProducer dataProducer = GetDataProducer(request, handler); if (request.HasBody()) { body.Connect(new BufferedConsumer( bufferedBody => { handler.RecordRequest(request, bufferedBody); _log.DebugFormat("Body: {0}", bufferedBody); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); }, error => { _log.DebugFormat("Error while reading body {0}", error.Message); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); } )); } else { response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); handler.RecordRequest(request, null); } _log.DebugFormat("End Processing request for : {0}:{1}", request.Method, request.Uri); }