This isn't quite a hello-world, because I want to show how to use macros for building HTTP services.
First, we need to tell Ruby to load webrick module and bind class name into RLisp namespace (there is no automatic importing of constants, maybe there should me):
(ruby-eval "require 'webrick'") ; import moduleNow let's create the server object and tell it to bind to port 1337 instead of default port 80. Configuration is simply a hash table:
(let HTTPServer (ruby-eval "WEBrick::HTTPServer"))
; Configure the serverNow we could basically send mount_proc message to server object to bind a lambda to URL.
(let config [Hash new])
[config set 'Port 1337]
; Tell the class to make us a server object
(let server (send HTTPServer 'new config))
; Tell server to call our Hello World handlerBut this is not very nice. Let's macro around this definition.
(send server 'mount_proc "/hello"
(lambda (req res)
[res body= "<html><body><h3>Hello, world!</h3></body></html>"]
[res field_set "Content-Type" "text/html"]
)
)
First let's make a macro that lets us bind more easily:
; Define a macro for HTML mountsNow we can rewrite the original handler to:
(defsyntax def-server-html-mount args
`(send ,[args get 0] 'mount_proc ,[args get 1]
(lambda (req res)
(send res 'field_set "Content-Type" "text/html")
(send res 'body= (do ,@(tl (tl args))))
(print res)
)
)
)
; Tell server to call our Hello World handlerThe mount is as good as it gets, but we'd still rather have nice syntax for HTML.
(def-server-html-mount server "/hello"
"<html><body><h3>Hello, world!</h3></body></html>"
)
So let's define a macro that creates html-generating functions:
; Define a macro for HTML tag functionAnd define a few such functions:
(defsyntax def-html-tag (tagname)
`(defun ,tagname args
(+
"<" (send ',tagname to_s) ">"
[args join]
"</" (send ',tagname to_s) ">"
)
)
)
(def-html-tag html)Could it be any more cute than that ?
(def-html-tag body)
(def-html-tag h3)
(def-server-html-mount server "/hello2"Happy about the results, we start the server:
(html (body (h3 "Macros Greet you")))
)
; Tell the server to go !RLisp is available for download from http://taw.chaosforge.org/rlisp/.
(send server 'start)
Previous posts about RLisp are here [1] and here [2].



3 comments:
Can you post here how does look http_server_hello.rl implemented in plain Ruby?
It looks remarkably similar:
require 'webrick'
# Configure the server
config = {:Port => 1337}
# Tell the class to make us a server object
server = WEBrick::HTTPServer.new(config)
# Tell server to call our Hello World handler
server.mount_proc("/hello") {|req,res|
res.body = "<html><body><h3>Hello, world!</h3></body></html>"
res["Content-Type"] = "text/html"
}
# Tell the server to go !
server.start
I am very happy to read this article..thanks for giving us this useful information. anti viral Read a useful article about tramadol tramadol
Post a Comment