-
-
Save sowawa/2947216 to your computer and use it in GitHub Desktop.
sinatra on mruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice!
made me smile tho ;)