Menu
Home
Create new Paste
Log in
UDA CGI
Code
Theme: cobalt
Theme: eclipse
Theme: elegant
Theme: monokai
Theme: neat
Theme: night
Theme: rubyblue
/// Requires https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff/blob/master/cgi.d class HelloWorld : Base { this(Cgi cgi){ super(cgi);} [Get("/?")] // Equivalent to [Uri("/?", Method.Get)] void indexGet() { echo("GET Hello, world!", "<br/>"); } [Post("/?")] void indexPost() { echo("POST Hello, world!", "<br/>"); } } mixin Main!HelloWorld; ///////////// public import arsd.cgi; import std.conv, std.regex; /** * Represents case request handler */ class Base { protected Cgi _cgi; protected UriBinding[] _binds; protected string[] _echos; /** * URL where application resides */ public string baseUrl; /** * Creates new Base instance * * Params: * cgi = CGI instance */ this(Cgi cgi) { _cgi = cgi; } /** * Writes text to client * * Params: * ... = Data to write */ public void echo(T...)(T s) { foreach(e; s) { _echos ~= to!string(e); } } /** * Dispatches request and calls handler that matches URI. */ public void dispatch() { auto uri = _cgi.pathInfo.dup; uri.chomp("/"); if(uri.startsWith(baseUrl)) { uri = uri[baseUrl.length..$]; } foreach(bind; _binds) { auto r = regex(bind.uri.pattern); auto m = match(uri, r); if(isRequestMethod(bind.uri.method) && m.captures.length > 0) { bind.handler(); } } _cgi.write(_echos.join("")); } protected bool isRequestMethod(Method method) { if(method == Method.Any) { return true; } else { return _cgi.requestMethod == method; } } } /** * Defines main controller */ mixin template Main(T) { /** * Handles request and registers handlers */ void handleRequest(Cgi cgi) { T main = new T(cgi); foreach(m; __traits(derivedMembers, T)) { foreach(attr; __traits(getAttributes, __traits(getMember, T, m))) { static if(typeof(attr).stringof == "Uri") { mixin("main._binds ~= UriBinding( attr, &main."~m~");"); } } } main.dispatch(); } mixin GenericMain!handleRequest; } /** * Request method */ enum Method { Get, Head, Post, Put, Delete, Any = 1024 } struct UriBinding { Uri uri; void delegate() handler; this(Uri uri, void delegate() handler) { this.uri = uri; this.handler = handler; } } struct Uri { string pattern; Method method; this(string pattern, Method method = Method.Any) { this.pattern = pattern; this.method = method; } } Uri Get(string pattern) { return Uri(pattern, Method.Get); } Uri Post(string pattern) { return Uri(pattern, Method.Post); }
Username
Message
reCAPTCHa
Add comment
Paste info
Author:
robik
Views:
183
Private:
no
Expires:
Never
Uploaded:
07.11.12 18:58
Tags:
attribute
attributes
Votes
:
0
Tweet
Actions
Download
Fork
Raw
×
Confirm
Are you sure you want to delete this paste?
There's no way back!
×
Confirm
Reason