Skip to content

Instantly share code, notes, and snippets.

@frankli0324
Created March 15, 2020 09:00
Show Gist options
  • Save frankli0324/dd393a40db65f1ac6cedb9545d2bd998 to your computer and use it in GitHub Desktop.
Save frankli0324/dd393a40db65f1ac6cedb9545d2bd998 to your computer and use it in GitHub Desktop.
flask request object port
namespace Foo {
public class Request {
HttpListenerContext context;
Task<int> read_body;
byte[] body = new byte[4096];
public Request (HttpListenerContext ctx) {
context = ctx;
read_body = context.Request.InputStream.ReadAsync (body, 0, 4096);
}
public string path {
get => context.Request.Url.PathAndQuery;
}
public IEnumerable<(string, string)> args {
get => context.Request.Url.Query
.Split ('&').Select ((query) => {
var x = query.Split ('=');
if (x.Length == 2)
return (
HttpUtility.UrlDecode (x[0]),
HttpUtility.UrlDecode (x[1])
);
return (x[0], null);
});
}
public async Task WaitFinishAsync () {
await read_body;
}
/// <<summary>
/// warning: throws inner exception if present
/// </summary>
public bool IsCompleted {
get {
if (read_body.IsCompleted)
if (read_body.IsCompletedSuccessfully)
return true;
else throw read_body.Exception;
return false;
}
}
public IEnumerable<(string, string)> form {
get => text.Split ('&').Select ((query) => {
var x = query.Split ('=');
if (x.Length == 2)
return (
HttpUtility.UrlDecode (x[0]),
HttpUtility.UrlDecode (x[1])
);
return (x[0], null);
});
}
public IEnumerable<(string, string)> headers {
get => context.Request.Headers.AllKeys.Select (x =>
(x, string.Join (',', context.Request.Headers.GetValues (x)))
);
}
public byte[] content {
get => IsCompleted ? body : null;
}
public string text {
get => IsCompleted ? Encoding.UTF8.GetString (body, 0, read_body.Result) : null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment