Azureで独自のハンドラ ( IIS と IHttpHandler ) で、独自のハンドラを追加できた。
これを応用して、IronRubyを動かしてみたい
まずは、HandlerとWeb.Config
前回の Azureで独自のハンドラ ( IIS と IHttpHandler ) を踏まえていきなりコードを書く。
IHttpHandler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.Scripting.Hosting;
namespace IronRubyHosting
{
public class HttpHandlerFactory : IHttpHandlerFactory
{
private static readonly object GlobalLock = new object();
private static HttpHandler Handler;
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
if (Handler == null)
{
lock (GlobalLock)
{
if (Handler == null)
{
try
{
Handler = new HttpHandler();
Handler.InitIronRuby();
}
catch (Exception e)
{
context.Response.StatusCode = 200;
return null;
}
}
}
}
return Handler;
}
public void ReleaseHandler(IHttpHandler/*!*/ handler)
{
}
}
public sealed class HttpHandler : IHttpHandler
{
// from IHttpHandler
public bool IsReusable
{
get { return true; }
}
// from IHttpHandler
public void ProcessRequest(HttpContext context)
{
lock (this)
{
try
{
HttpServerProcess(context);
}
catch (Exception ex)
{
var s = "<html><head><title>error</title></head>\n";
s += "<body><h1>Exception</h1>\n";
s += "<pre>\n";
s += System.Web.HttpUtility.HtmlEncode( ex.Message );
s += "\n";
s += System.Web.HttpUtility.HtmlEncode( ex.StackTrace );
s += "\n";
s += "</pre>\n";
s += "</body></html>\n";
context.Response.Write(s);
context.Response.ContentType = "text/html; charset=utf-8";
}
}
}
ScriptRuntime runtime;
ScriptEngine engine;
public void InitIronRuby()
{
runtime = IronRuby.Ruby.CreateRuntime();
engine = runtime.GetEngine("rb");
}
private void HttpServerProcess(HttpContext context)
{
var req = context.Request;
var res = context.Response;
var scope = engine.CreateScope();
scope.SetVariable("req", req);
scope.SetVariable("res", res);
var src = @"
$KCODE='u'
s = <<EOS.ToString
<html>
<head><title>タイトル</title></head>
<body>hello I'm IronRuby</body>
</html>
EOS
res.Write( s );
res.ContentType = 'text/html; charset=utf-8'
";
var source = engine.CreateScriptSourceFromString(src);
source.Execute(scope);
}
}
}
基本は、前回のHTTP Handlerをベースとしている。 また、IronRubyとの繋ぎ込みは、 「 C# から IronRuby スクリプトの呼び出し 」 「 C# から IronRuby スクリプトの呼び出し(C#からIronRubyの変数に値を設定してみる) 」 「 C# から IronRuby スクリプトの呼び出し方法 」 等で記載した方法を用いている。
IISへの応答は Ruby Script で行っている。 この時、 .NET クラスへの文字列を渡す所があるので、ToString等を用いている。
おわりに
とりあえず、IISから直接IronRubyへのつなぎ込みが出来た。
ちなみに、この状況が 「 [速報]AzureからIronRubyを起動(疎通確認) 」 である。
次は、RackやSinatraとの繋ぎ込みである


コメントする