1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: modlisp -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
6 ;;;; Purpose: Utility functions for modlisp package
7 ;;;; Programmer: Kevin M. Rosenberg
8 ;;;; Date Started: Dec 2002
11 ;;;; *************************************************************************
13 (in-package #:modlisp)
15 (defun format->string (fmt)
22 (defun format-string (fmt headers)
24 ,(format->string fmt))
27 (defmacro write-response ((&key headers len (status "200 OK")) &body body)
28 (let ((result (gensym "RES-")))
30 (write-header-line "Status" ,status)
31 (dolist (hdr ,headers)
32 (write-header-line (car hdr) (cdr hdr)))
34 `((write-header-line "Content-Length" ,len)
35 (write-header-line "Keep-Socket" "1")
36 (write-header-line "Connection" "Keep-Alive")))
37 (write-string "end" *modlisp-socket*)
38 (write-char #\NewLine *modlisp-socket*)
39 (let ((,result (progn ,@body)))
40 (,(if len 'force-output 'finish-output) *modlisp-socket*)
41 (setq *close-modlisp-socket* ,(not len))
44 (defmacro with-ml-page ((&key (format :html) (precompute t) headers)
47 `(output-ml-page ,format (with-output-to-string (*modlisp-socket*) ,@body) :headers ,headers)
48 `(write-response (:headers (format-string ,format ,headers)) ,@body)))
50 (defun redirect-to-location (url)
51 (write-response (:status "307 Temporary Redirect" :headers `(("Location" . ,url)))))
53 (defmacro output-ml-page (format html &key headers)
54 (let ((str (gensym "STR-")))
56 (write-response (:len (format nil "~d" (length ,str))
57 :headers (format-string ,format ,headers))
58 (write-string ,str *modlisp-socket*)))))
60 (defun output-html-page (str &key headers)
61 (output-ml-page :html str :headers headers))
63 (defun output-xml-page (str &key headers)
64 (output-ml-page :xml str :headers headers))
66 ;; Utility functions for library users
68 (defun query-to-alist (posted-string &key (keyword t))
69 "Converts a posted string to an assoc list of keyword names and values,
70 \"a=1&bc=demo\" => ((:a . \"1\") (:bc . \"demo\"))"
73 (dolist (name=val (kmrcl:delimited-string-to-list posted-string #\&)
75 (let ((name-val-list (kmrcl:delimited-string-to-list name=val #\=)))
76 (if (= 2 (length name-val-list))
77 (destructuring-bind (name val) name-val-list
78 (push (cons (if keyword
79 (kmrcl:ensure-keyword name)
81 (kmrcl:decode-uri-query-string val))
83 (cmsg-c :debug "Invalid number of #\= in ~S" name-val-list)))))))