public Task Invoke(IDictionary<string, object> env) { var request = new Request(env); var response = new Response(env) { ContentType = "text/html", }; var wilson = "left - right\r\n123456789012\r\nhello world!\r\n"; var href = "?flip=left"; if (request.Query["flip"] == "left") { wilson = wilson.Split(new[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) .Select(line => new string(line.Reverse().ToArray())) .Aggregate("", (agg, line) => agg + line + System.Environment.NewLine); href = "?flip=right"; } return TimerLoop(350, () => response.Write("<title>Hutchtastic</title>"), () => response.Write("<pre>"), () => response.Write(wilson), () => response.Write("</pre>"), () => { if (request.Query["flip"] == "crash") { throw new ApplicationException("Wilson crashed!"); } }, () => response.Write("<p><a href='" + href + "'>flip!</a></p>"), () => response.Write("<p><a href='?flip=crash'>crash!</a></p>")); }
public void ResponseMayHaveContentLength() { AppDelegate app = call => { var response = new Response(); response.Headers.SetHeader("Content-Length", "12"); response.Write("Hello world."); return response.EndAsync(); }; using (ServerFactory.Create(app, 8090, null)) { var request = (HttpWebRequest)WebRequest.Create("http://localhost:8090/"); string text; using (var response = request.GetResponse()) { using (var stream = response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { text = reader.ReadToEnd(); } } } Assert.That(text, Is.EqualTo("Hello world.")); } }
public static IResponse MyAppLogic(IRequest rawRequest) { var request = new Request(rawRequest); var response = new Response().SetHeader("content-type", "text/plain"); var errors = Owin.Lint.ErrorMessagesFor(rawRequest); response.Write("{0} {1}\n\n", request.Method, request.Uri); if (errors.Length == 0) response.Write("The IRequest is valid!"); else foreach (string message in errors) response.Write("Error: {0}\n", message); return response; }
public static AppDelegate AsyncApp() { return (env, result, fault) => { var request = new Request(env); var response = new Response(result) { ContentType = "text/html", }; var wilson = "left - right\r\n123456789012\r\nhello world!\r\n"; ThreadPool.QueueUserWorkItem(_ => { try { var href = "?flip=left"; if (request.Query["flip"] == "left") { wilson = wilson.Split(new[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) .Select(line => new string(line.Reverse().ToArray())) .Aggregate("", (agg, line) => agg + line + System.Environment.NewLine); href = "?flip=right"; } response.Start(() => TimerLoop(350, response.Error, () => response.Write("<title>Hutchtastic</title>"), () => response.Write("<pre>"), () => response.Write(wilson), () => response.Write("</pre>"), () => { if (request.Query["flip"] == "crash") { throw new ApplicationException("Wilson crashed!"); } }, () => response.Write("<p><a href='" + href + "'>flip!</a></p>"), () => response.Write("<p><a href='?flip=crash'>crash!</a></p>"), response.End)); } catch (Exception ex) { fault(ex); } }); }; }
public static AppDelegate Middleware(AppDelegate app) { return call => { Action<Exception, Action<byte[]>> showErrorMessage = (ex, write) => ErrorPage(call, ex, text => { var data = Encoding.ASCII.GetBytes(text); write(data); }); Func<Exception, Task<ResultParameters>> showErrorPage = ex => { var response = new Response() { Status = "500 Internal Server Error", ContentType = "text/html" }; showErrorMessage(ex, data => response.Write(data)); return response.EndAsync(); }; try { return app(call) .Then(result => { if (result.Body != null) { var nestedBody = result.Body; result.Body = stream => { try { return nestedBody(stream).Catch( errorInfo => { showErrorMessage(errorInfo.Exception, data => stream.Write(data, 0, data.Length)); return errorInfo.Handled(); }); } catch (Exception ex) { showErrorMessage(ex, data => stream.Write(data, 0, data.Length)); return TaskHelpers.Completed(); } }; } return result; }) .Catch(errorInfo => { return errorInfo.Handled(showErrorPage(errorInfo.Exception).Result); }); } catch (Exception exception) { return showErrorPage(exception); } }; }
public override IResponse Call(IRequest rawRequest) { Request request = new Request(rawRequest); Response response = new Response(); if (request.Uri == "/boom") throw new Exception("BOOM!"); response.ContentType = "text/plain"; response.Write("{0} {1}\n\n", request.Method, request.Uri); foreach (KeyValuePair<string,string> param in request.Params) response.Write("Param {0} = {1}\n", param.Key, param.Value); foreach (KeyValuePair<string,IEnumerable<string>> header in request.Headers) foreach (string value in header.Value) response.Write("Header {0} = {1}\n", header.Key, value); return response; }
public static AppDelegate Middleware(AppDelegate app) { return (call, callback) => { Action<Exception, Action<ArraySegment<byte>>> showErrorMessage = (ex, write) => ErrorPage(call, ex, text => { var data = Encoding.ASCII.GetBytes(text); write(new ArraySegment<byte>(data)); }); Action<Exception> showErrorPage = ex => { var response = new Response(callback) { Status = "500 Internal Server Error", ContentType = "text/html" }; response.Start(() => { showErrorMessage(ex, data => response.Write(data)); response.End(); }); }; try { app(call, (result, error) => { if (error != null) { showErrorPage(error); } else { var body = result.Body; result.Body = (write, end, cancel) => { showErrorPage = ex => { if (ex != null) { showErrorMessage(ex, data => write(data, null)); } end(null); }; body.Invoke(write, showErrorPage, cancel); }; callback(result, null); } }); } catch (Exception exception) { showErrorPage(exception); } }; }
public void Adds_connection_close_response_header_if_no_length_or_encoding() { Response expectedResponse = new Response(200); expectedResponse.Write("12345"); expectedResponse.Write("67890"); var app = new StaticApp(expectedResponse); var requestDelegate = new GateRequestDelegate(app.Invoke, new Dictionary<string, object>()); requestDelegate.OnRequest(new HttpRequestHead() { }, null, mockResponseDelegate); Assert.That(app.Call.Body, Is.Null); Assert.That(mockResponseDelegate.Head.Headers.Keys, Contains.Item("Connection")); Assert.That(mockResponseDelegate.Head.Headers["Connection"], Is.EqualTo("close")); Assert.That(mockResponseDelegate.Body, Is.Not.Null); var body = mockResponseDelegate.Body.Consume(); Assert.That(body.Buffer.GetString(), Is.EqualTo("1234567890")); Assert.That(body.GotEnd, Is.True); }
public static AppDelegate Middleware(AppDelegate app) { return (env, result, fault) => { Action<Exception, Action<ArraySegment<byte>>> showErrorMessage = (ex, write) => ErrorPage(env, ex, text => { var data = Encoding.ASCII.GetBytes(text); write(new ArraySegment<byte>(data)); }); Action<Exception> showErrorPage = ex => { var response = new Response(result) { Status = "500 Internal Server Error", ContentType = "text/html" }; response.Start(() => { showErrorMessage(ex, data => response.Write(data)); response.End(); }); }; try { app( env, (status, headers, body) => result( status, headers, (write, flush, end, token) => { showErrorPage = ex => { if (ex != null) { showErrorMessage(ex, data => write(data)); } end(null); }; body( write, flush, showErrorPage, token); }), ex => showErrorPage(ex)); } catch (Exception exception) { showErrorPage(exception); } }; }
public static AppDelegate App() { return call => { var request = new Request(call); var response = new Response { Buffer = true, ContentType = "text/html" }; var wilson = "left - right\r\n123456789012\r\nhello world!\r\n"; var href = "?flip=left"; if (request.Query["flip"] == "left") { wilson = wilson.Split(new[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) .Select(line => new string(line.Reverse().ToArray())) .Aggregate("", (agg, line) => agg + line + System.Environment.NewLine); href = "?flip=right"; } response.Write("<title>Wilson</title>"); response.Write("<pre>"); response.Write(wilson); response.Write("</pre>"); if (request.Query["flip"] == "crash") { throw new ApplicationException("Wilson crashed!"); } response.Write("<p><a href='" + href + "'>flip!</a></p>"); response.Write("<p><a href='?flip=crash'>crash!</a></p>"); response.End(); return response.GetResultAsync(); }; }
public override IResponse Call(IRequest request) { Response response = new Response(); switch (request.Uri) { case "/badResponse": response.SetBody(5); // add unkown object type into body break; default: response.Write("You requested {0} {1}", request.Method, request.Uri); break; } return response; }
public void Normal_request_should_pass_through_unchanged() { var stack = Build(b => b .UseShowExceptions() .UseFunc<AppDelegate>(_ => appCall => { Response appResult = new Response(200); appResult.Headers.SetHeader("Content-Type", "text/plain"); appResult.Headers.SetHeader("Content-Length", "5"); appResult.Write("Hello"); return appResult.EndAsync(); })); ResultParameters result = stack(new Request().Call).Result; Assert.That(result.Status, Is.EqualTo(200)); Assert.That(ReadBody(result.Body), Is.EqualTo("Hello")); }
public void Normal_request_should_pass_through_unchanged() { var stack = Build(b => b .UseShowExceptions() .UseFunc<AppFunc>(_ => appEnv => { Response appResult = new Response(appEnv) { StatusCode = 200 }; appResult.Headers.SetHeader("Content-Type", "text/plain"); appResult.Headers.SetHeader("Content-Length", "5"); appResult.Write("Hello"); return TaskHelpers.Completed(); })); Request request = Request.Create(); Response response = new Response(request.Environment); MemoryStream buffer = new MemoryStream(); response.OutputStream = buffer; stack(request.Environment).Wait(); Assert.That(response.StatusCode, Is.EqualTo(200)); Assert.That(ReadBody(buffer), Is.EqualTo("Hello")); }
public void Write_calls_will_spool_until_finish_is_called() { var resp = new Response() { Status = "200 Yep" }; resp.Write("this"); resp.Write("is"); resp.Write("a"); resp.Write("test"); ResultParameters result = resp.EndAsync().Result; Assert.That(result.Status, Is.EqualTo(200)); var data = Encoding.UTF8.GetString(Consume(result.Body)); Assert.That(data, Is.EqualTo("thisisatest")); }
public void Does_not_add_content_length_response_header_if_transfer_encoding_chunked() { Response expectedResponse = new Response(200); expectedResponse.Headers.SetHeader("Transfer-Encoding", "chunked"); expectedResponse.Write("12345"); expectedResponse.Write("67890"); var app = new StaticApp(expectedResponse); var requestDelegate = new GateRequestDelegate(app.Invoke, new Dictionary<string, object>()); requestDelegate.OnRequest(new HttpRequestHead() { }, null, mockResponseDelegate); Assert.That(app.Call.Body, Is.Null); Assert.IsFalse(mockResponseDelegate.Head.Headers.Keys.Contains("Content-Length"), "should not contain Content-Length"); // chunks are not chunked-encoded at this level. eventually kayak will do this automatically. Assert.That(mockResponseDelegate.Body, Is.Not.Null); var body = mockResponseDelegate.Body.Consume(); Assert.That(body.Buffer.GetString(), Is.EqualTo("1234567890")); Assert.That(body.GotEnd, Is.True); }
private static AppFunc Fail(int status, string body, string headerName = null, string headerValue = null) { return env => { Response response = new Response(env); response.StatusCode = status; response.Headers .SetHeader("Content-Type", "text/plain") .SetHeader("Content-Length", body.Length.ToString(CultureInfo.InvariantCulture)) .SetHeader("X-Cascade", "pass"); if (headerName != null && headerValue != null) { response.Headers.SetHeader(headerName, headerValue); } response.Write(body); return response.EndAsync(); }; }
public void Write_calls_will_spool_until_finish_is_called() { var env = CreateEmptyEnvironment(); MemoryStream buffer = new MemoryStream(); env.Set("owin.ResponseBody", buffer); var resp = new Response(env) { Status = "200 Yep" }; resp.Write("this"); resp.Write("is"); resp.Write("a"); resp.Write("test"); Assert.That(env.Get<int>("owin.ResponseStatusCode"), Is.EqualTo(200)); buffer.Seek(0, SeekOrigin.Begin); var data = Encoding.UTF8.GetString(buffer.ToArray()); Assert.That(data, Is.EqualTo("thisisatest")); }
public void Write_calls_will_spool_until_finish_is_called() { var resp = new Response(Result) { Status = "200 Yep" }; resp.Write("this"); resp.Write("is"); resp.Write("a"); resp.Write("test"); resp.End(); Assert.That(_status, Is.EqualTo("200 Yep")); var data = Encoding.UTF8.GetString(Consume()); Assert.That(data, Is.EqualTo("thisisatest")); }