簡単なHTTPサーバを作れないか試してみた

HudsonのリモートAPIを試すのに毎回ホンモノにアクセスするのもしんどいので,スタブ作れないかなとモガモガしてみた。
てなわけで,

(↑)ここらへん参考にして,こんなコード書いてみたよ。

import groovy.text.*
import groovy.net.http.*

def params = [:] // some map with parameters for the template
def templates = [
  "/hudson/api/xml": new GStringTemplateEngine().createTemplate(new File("hudson.xml").newReader("UTF-8"))
]

def server = new HTTPServer()
server.get = {input, output, uri, version ->
  output << header()
  def c = templates[uri].make(params).toString()
  println c
  output << c
}
server.startServer(new ServerSocket(9991))

def header() {
  """HTTP/1.1 200 OK
Date: ${new Date()}
Content-Type: text/html; charset=UTF-8

"""
}

テンプレにつかってみた hudson.xml ってのは,こんなの

<hudson>
  <description>&lt;h2&gt;Continuous Integration Builds for NetBeans Projects&lt;/h2&gt;
Services on this machine are described at: &lt;a href="http://wiki.netbeans.org/wiki/view/DeadlockMachine"&gt;DeadlockMachine&lt;/a&gt;
&lt;p/&gt;&lt;p/&gt;&lt;p/&gt;</description>
  <job>
    <name>analytics-server</name>
    <url>http://localhost:9991/hudson/job/analytics-server/</url>
    <color>blue</color>
  </job>
  <job>
    <name>apitest</name>
    <url>http://localhost:9991/hudson/job/apitest/</url>
    <color>blue</color>
  </job>
  <primaryView>
    <name>All</name>
    <url>http://localhost:9991/hudson/</url>
  </primaryView>
  <slaveAgentPort>0</slaveAgentPort>
  <view>
    <name>All</name>
    <url>http://localhost:9991/hudson/</url>
  </view>
</hudson>

URIに応じて,それっぽいレスポンス返せりゃ十分スタブになるとおもうんで,こんなもんでいいだろう。ビバ,RESTfulと言ったところか。:-)


あーそうそう,groovy.net.httpパッケージは,XMLRPC moduleに含まれているので,このjarファイルを$GROOVY_HOME/libに放り込んでおこう。


ps.
やりかた調べている過程でこんなのも見つけた。
#みんな,何語でコメントしてるのかな〜?

groovyコマンドのオプション(-l)使う発想は無かった。

- web.groovy -
if (init) data = "";

if (line.size() > 0) {
  data += line + "\n"
} else {
  println "HTTP/1.0 200 OK\n"
  println data
  return "success"
}

んで,こうつかう。

> groovy -l 8000 web.groovy

何の役に立つかは知らん。:-P