Skip to content

Instantly share code, notes, and snippets.

@gchiu
Created April 5, 2013 23:00
Show Gist options
  • Save gchiu/5323356 to your computer and use it in GitHub Desktop.
Save gchiu/5323356 to your computer and use it in GitHub Desktop.
Mini http read
; mini-http is a minimalistic http implementation
mini-http: func [ url [url!] method [word! string!] code [string!] timeout [integer!]
/local url-obj http-request payload result port
][
http-request: {$method $path HTTP/1.0
Host: $host
User-Agent: Mozilla/5.0
Accept: text/html
Referer: http://$host
Content-Length: $len
Content-Type: text/plain; charset=UTF-8
$code}
url-obj: construct/with sys/decode-url url make object! copy [port-id: 80 path: ""]
if empty? url-obj/path [ url-obj/path: copy "/" ]
payload: reword http-request reduce [
'method method
'path url-obj/path
'host url-obj/host
'len length? code
'code code
]
probe payload
port: make port! rejoin [tcp:// url-obj/host ":" url-obj/port-id]
port/awake: func [event] [
switch/default event/type [
lookup [open event/port false ]
connect [write event/port to binary! join payload newline false]
wrote [read event/port false]
read done [
; probe event/port/data
result: to-string event/port/data true ]
][ true ]
]
open port
either port? wait [ port timeout ][
result
][ ; timeout
none
]
]
extract-http-response: func [ http-text [string!]
/local result code bodytext server-code
][
digit: charset [ #"0" - #"9" ]
either parse http-text [ thru "HTTP/1." [ "0" | "1" ] space copy code 3 digit space copy server-code to newline
thru "^/^/^/" copy bodytext to end ][
bodytext
][
make object! compose [ error: (server-code) code: (code) ]
]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment