factor/extra/http/server/actions/actions.factor

69 lines
1.9 KiB
Factor
Raw Normal View History

2008-03-03 03:19:36 -05:00
! Copyright (C) 2008 Slava Pestov.
! See http://factorcode.org/license.txt for BSD license.
2008-03-20 16:30:59 -04:00
USING: accessors sequences kernel assocs combinators
2008-03-11 04:39:09 -04:00
http.server http.server.validators http hashtables namespaces
fry continuations locals boxes xml.entities html.elements io ;
2008-03-03 03:19:36 -05:00
IN: http.server.actions
2008-03-11 04:39:09 -04:00
SYMBOL: params
SYMBOL: validation-message
: render-validation-message ( -- )
validation-message get value>> [
<span "error" =class span>
escape-string write
</span>
] when* ;
2008-03-11 04:39:09 -04:00
TUPLE: action init display submit get-params post-params ;
2008-03-03 03:19:36 -05:00
2008-03-05 22:38:15 -05:00
: <action>
action new
2008-03-11 04:39:09 -04:00
[ ] >>init
[ <400> ] >>display
[ <400> ] >>submit ;
2008-03-03 03:19:36 -05:00
2008-03-15 07:22:47 -04:00
:: validate-param ( name validator assoc -- )
name assoc at validator with-validator name set ; inline
2008-03-11 04:39:09 -04:00
: action-params ( validators -- error? )
2008-03-15 07:22:47 -04:00
validation-failed? off
params get '[ , validate-param ] assoc-each
validation-failed? get ;
2008-03-05 22:38:15 -05:00
2008-03-11 04:39:09 -04:00
: handle-get ( -- response )
action get get-params>> action-params [ <400> ] [
action get [ init>> call ] [ display>> call ] bi
] if ;
2008-03-05 22:38:15 -05:00
2008-03-11 04:39:09 -04:00
: handle-post ( -- response )
2008-03-05 22:38:15 -05:00
action get post-params>> action-params
2008-03-11 04:39:09 -04:00
[ <400> ] [ action get submit>> call ] if ;
: validation-failed ( -- * )
action get display>> call exit-with ;
: validation-failed-with ( string -- * )
validation-message get >box
validation-failed ;
M: action call-responder* ( path action -- response )
2008-03-17 05:31:13 -04:00
'[
2008-04-25 04:23:47 -04:00
, [ CHAR: / = ] right-trim empty? [
, action set
request get
<box> validation-message set
[ request-params params set ]
[
method>> {
{ "GET" [ handle-get ] }
{ "HEAD" [ handle-get ] }
{ "POST" [ handle-post ] }
} case
] bi
2008-04-25 04:23:47 -04:00
] [
<404>
] if
2008-03-17 05:31:13 -04:00
] with-exit-continuation ;