Skip to content

Instantly share code, notes, and snippets.

@sowawa
Forked from mattn/sinachiku.rb
Created June 18, 2012 07:00
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sowawa/2947216 to your computer and use it in GitHub Desktop.
Save sowawa/2947216 to your computer and use it in GitHub Desktop.
sinatra on mruby
require 'HTTP'
require 'UV'
module Sinachiku
@routes = { 'GET' => [], 'POST' => [] }
def self.route(method, path, opts, &block)
@routes[method] << [path, opts, block]
end
def self.do(r)
@routes[r.method].each {|path|
if path[0] == r.path
body = path[2][r]
return "HTTP/1.0 200 OK\r\nContent-Length: #{body.size}\r\n\r\n#{body}"
end
}
return "HTTP/1.0 404 Not Found\r\nContent-Length: 10\r\n\r\nNot Found\n"
end
def self.run()
s = UV::TCP.new()
s.bind(UV::ip4_addr('127.0.0.1', 8888))
s.data = []
s.listen(50) {|x|
return if x != 0
c = s.accept()
c.read_start {|b|
h = HTTP::Parser.new()
h.parse(b) {|r|
i = b.index("\r\n\r\n") + 4
r.body = b.slice(i, b.size - i)
c.write(::Sinachiku.do(r)) {|x| c.close }
}
}
s.data << c
}
while 1 do
# NOTE: must be call run_once to run GC.
UV::run_once()
end
end
end
module Kernel
def get(path, opts={}, &block)
::Sinachiku.route 'GET', path, opts, &block
end
def post(path, opts={}, &block)
::Sinachiku.route 'POST', path, opts, &block
end
end
get "/foo.js" do
'
$(function() {
$("#foo").text("hello world");
})
'
end
get "/" do
'
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/foo.js"></script>
<div id="foo"></div>
<form action="/add" method="post">
<label for="name"/>お名前</label>
<input type="text" id="name" name="name" value="">
<input type="submit">
</form>
'
end
post "/add" do |r|
r.body
end
Sinachiku.run
@mattetti
Copy link

nice!

while 1 do
      # NOTE: must be call run_once to run GC.
      UV::run_once()
    end

made me smile tho ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment