factor/library/httpd/http-common.factor

89 lines
2.2 KiB
Factor
Raw Normal View History

2005-04-19 20:28:01 -04:00
! Copyright (C) 2003, 2005 Slava Pestov, Chris Double
2004-07-16 02:26:21 -04:00
IN: httpd
USING: kernel lists namespaces parser sequences stdio streams
2005-04-19 20:28:01 -04:00
strings url-encoding ;
2004-07-16 02:26:21 -04:00
: print-header ( alist -- )
[ unswons write ": " write url-encode print ] each ;
2004-07-16 02:26:21 -04:00
: response ( header msg -- )
"HTTP/1.0 " write print print-header ;
2004-07-16 02:26:21 -04:00
: error-body ( error -- body )
"<html><body><h1>" swap "</h1></body></html>" cat3 print ;
2004-07-16 02:26:21 -04:00
: error-head ( error -- )
2004-07-16 02:26:21 -04:00
dup log-error
[ [[ "Content-Type" "text/html" ]] ] over response ;
: httpd-error ( error -- )
#! This must be run from handle-request
error-head
"head" "method" get = [ terpri error-body ] unless ;
: bad-request ( -- )
[
! Make httpd-error print a body
"get" "method" set
"400 Bad request" httpd-error
] with-scope ;
2004-07-16 02:26:21 -04:00
: serving-html ( -- )
[ [[ "Content-Type" "text/html" ]] ]
"200 Document follows" response terpri ;
: serving-text ( -- )
[ [[ "Content-Type" "text/plain" ]] ]
"200 Document follows" response terpri ;
: redirect ( to -- )
"Location" swons unit
"301 Moved Permanently" response terpri ;
: directory-no/ ( -- )
[
"request" get , CHAR: / ,
"raw-query" get [ CHAR: ? , , ] when*
] make-string redirect ;
: header-line ( alist line -- alist )
": " split1 dup [ cons swons ] [ 2drop ] ifte ;
: (read-header) ( alist -- alist )
2005-02-14 22:15:02 -05:00
read-line dup
2005-04-19 20:28:01 -04:00
empty? [ drop ] [ header-line (read-header) ] ifte ;
2004-07-16 02:26:21 -04:00
: read-header ( -- alist )
[ ] (read-header) ;
2004-07-16 02:26:21 -04:00
: content-length ( alist -- length )
"Content-Length" swap assoc parse-number ;
2004-07-16 02:26:21 -04:00
: query>alist ( query -- alist )
dup [
"&" split [
"=" split1
dup [ url-decode ] when swap
dup [ url-decode ] when swap cons
] map
] when ;
2004-08-19 19:21:40 -04:00
: read-post-request ( header -- alist )
2005-02-14 22:15:02 -05:00
content-length dup [ read query>alist ] when ;
: log-user-agent ( alist -- )
"User-Agent" swap assoc* [
unswons [ , ": " , , ] make-string log
] when* ;
: prepare-url ( url -- url )
#! This is executed in the with-request namespace.
"?" split1
dup "raw-query" set query>alist "query" set
dup "request" set ;
: prepare-header ( -- )
read-header dup "header" set
dup log-user-agent
read-post-request "response" set ;