Web Development in Racket | Schema Programming Part 14
Racket includes a production-grade web server. But it's not just a standard server—it supports Continuations-based Web (or "Stateful") Servlets.
Advertisement
A Simple Servlet
#lang racket
(require web-server/servlet
web-server/servlet-env)
(define (start request)
(response/xexpr
'(html
(head (title "My Racket Blog"))
(body (h1 "Hello World")))))
(serve/servlet start)
This spins up a server on localhost:8000 executing the start function for each request.
Interaction (The Magic Part)
In most frameworks, if you want to ask a user a question, you render a form, point the action to a new route, and save state in a database. In Racket, you just... ask.
(define (start request)
(define name (get-user-input))
(response/xexpr `(html (body (h1 ,(string-append "Hello " name))))))
(define (get-user-input)
(define req
(send/suspend
(lambda (k-url)
(response/xexpr
`(html (body (form ([action ,k-url])
(input ([name "user"]))
(input ([type "submit"])))))))))
(extract-binding/single 'user (request-bindings req)))
send/suspend pauses the function, sends the form to the browser, and only continues when the user submits! The standard Racket web server handles the "back button" and expired links automatically.
Advertisement
Summary
For specialized applications, Racket's continuation-based server drastically simplifies flow control, making web interaction code look like a simple console script.
Which Racket function pauses execution to send a page to the user and waits for a response?
Md Nasim Sheikh
Software Developer at softexForge