Wednesday, October 13, 2010

A stateful web counter in Racket

The idea of using Racket as a stateful web server is really beginning to attract me interest. I present below a simple web counter. Each time you click on the ++ link, it increments the counter. If you start it in a new tab/window, then it begins at 0. So each tab has its own state.

#lang racket
;;;; a stateful web server

(require web-server/formlets

(define (counter request (count 0))    
   (lambda (k-url)
     `(html (head (title "Counter"))
             (p "Computer says: " ,(number->string count))
             (a ([href 
                  ,(k-url (lambda (request)
                                (counter (redirect/get) (+ 1 count))))
                  ]) "++")
             (p "Enjoy!"))))))

(define log-file 
   (build-path (find-system-path 'home-dir) ;(expand-user-path "~") 
; would this work better?:
; e.g. (list (build-path "js") (build-path "css"))

;;; Start the server
(serve/servlet counter 
               #:port 8080 
               #:listen-ip #f 
               #:log-file log-file 
               #:servlet-path "/counter.rkt")

No comments: