factor/libs/http.factor

76 lines
1.7 KiB
Factor
Raw Permalink Normal View History

! Copyright (C) 2003, 2005 Slava Pestov
IN: http
2006-05-25 00:06:50 -04:00
USING: errors hashtables io kernel math namespaces parser
2006-01-23 18:01:46 -05:00
sequences strings ;
2005-11-29 23:49:59 -05:00
: header-line ( line -- )
": " split1 dup [ swap set ] [ 2drop ] if ;
2005-11-29 23:49:59 -05:00
: (read-header) ( hash -- hash )
readln dup
2005-09-24 15:21:17 -04:00
empty? [ drop ] [ header-line (read-header) ] if ;
2004-07-16 02:26:21 -04:00
2005-11-29 23:49:59 -05:00
: read-header ( -- hash )
[ (read-header) ] make-hash ;
2004-07-16 02:26:21 -04:00
2006-01-02 00:51:03 -05:00
: url-quotable? ( ch -- ? )
#! In a URL, can this character be used without
#! URL-encoding?
dup letter?
over LETTER? or
over digit? or
swap "/_?." member? or ; foldable
: url-encode ( str -- str )
[
[
dup url-quotable? [
,
] [
2005-06-15 23:27:28 -04:00
CHAR: % , >hex 2 CHAR: 0 pad-left %
2005-09-24 15:21:17 -04:00
] if
] each
2005-08-25 15:27:38 -04:00
] "" make ;
2005-09-21 01:12:16 -04:00
: catch-hex> ( str -- n/f )
#! Push f if string is not a valid hex literal.
[ hex> ] catch [ drop f ] when ;
: url-decode-hex ( index str -- )
2dup length 2 - >= [
2drop
] [
2005-09-16 22:47:28 -04:00
>r 1+ dup 2 + r> subseq catch-hex> [ , ] when*
2005-09-24 15:21:17 -04:00
] if ;
: url-decode-% ( index str -- index str )
2dup url-decode-hex >r 3 + r> ;
: url-decode-+-or-other ( index str ch -- index str )
2005-09-16 22:47:28 -04:00
dup CHAR: + = [ drop CHAR: \s ] when , >r 1+ r> ;
: url-decode-iter ( index str -- )
2dup length >= [
2drop
] [
2dup nth dup CHAR: % = [
drop url-decode-%
] [
url-decode-+-or-other
2005-09-24 15:21:17 -04:00
] if url-decode-iter
] if ;
: url-decode ( str -- str )
2005-08-25 15:27:38 -04:00
[ 0 swap url-decode-iter ] "" make ;
2006-01-23 18:01:46 -05:00
: build-url ( path query-params -- str )
[
swap % dup hash-empty? [
"?" %
2006-01-23 20:05:39 -05:00
dup hash>alist
2006-01-23 18:01:46 -05:00
[ [ url-encode ] map "=" join ] map "&" join %
] unless drop
] "" make ;
2006-11-28 21:57:29 -05:00
PROVIDE: libs/http ;