Skip to content

Instantly share code, notes, and snippets.

@jessealama
Last active February 6, 2017 06:02
Show Gist options
  • Save jessealama/a276e995f96351c11997dedd9a544bf4 to your computer and use it in GitHub Desktop.
Save jessealama/a276e995f96351c11997dedd9a544bf4 to your computer and use it in GitHub Desktop.
#lang racket
(require web-server/servlet
web-server/servlet-env
web-server/templates)
(define html-utf-8-mime-type
"text-html; charset=utf-8")
(define html-utf-8-mime-type/bytes
(string->bytes/utf-8 html-utf-8-mime-type))
(define (respond-html code message headers body)
(response/full code
(string->bytes/utf-8 message)
(current-seconds)
html-utf-8-mime-type/bytes
headers
(list (string->bytes/utf-8 body))))
(define (not-found req)
(let ([uri (url->string (request-uri req))])
(respond-html 404
"Not Found"
empty
(include-template "not-found.html"))))
(define (hi thing query-params)
(include-template "hi.html"))
(define (not-allowed method)
(include-template "not-allowed.html"))
(define (hello req)
(respond-html 200
"OK"
empty
(hi "espresso"
(url-query (request-uri req)))))
(define (method-not-allowed req)
(respond-html 405
"Method Not Allowed"
empty
(not-allowed (request-method req))))
(define-values (dispatcher _)
(dispatch-rules
[("hello") #:method "get" hello]
[("hello") #:method (regexp ".*") method-not-allowed]
[else not-found]))
;; after loading this file, launch the server by evaluating
;; (serve/servlet dispatcher #:servlet-regexp #rx"")
<!doctype html>
<html>
<head>
<title>Most well-defined @|thing| in the Europe!</title>
</head>
<body>
<h1>Works!</h1>
<h2>Correct!</h2>
@unless[(empty? query-params)]{
<h3>Fast!</h3>
|@(include-template "list.html")
}
</body>
</html>
<dl>
@in[q query-params]{
<dt>@(car q)</dt>
<dd>@(cdr q)</dd>
}
</dl>
<!doctype html>
<html>
<head>
<title>Angry Face</title>
</head>
<body>
<h1>What are you trying to do?</h1>
<p>The @|method| HTTP method is not allowed.</p>
</body>
</html>
<!doctype html>
<html>
<head>
<title>Sad Face</title>
</head>
<body>
<h1>What are you looking for?</h1>
<p>There was nothing found at</p>
<pre>@|uri|</pre>
</body>
</html>
@jessealama
Copy link
Author

A skeletal Racket web server based on conventional URL dispatching. No continuations. There is only one route, hello, which responds to GET requests in one way, and to all other HTTP methods in another way. A fallback method handles all other URLs (and methods).

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