# HG changeset patch # User Mike Pavone # Date 1376184374 25200 # Node ID 729dc894e61c5c6b452cc48b7e50b2dd219f1968 # Parent d81de309a51f28335afaecea41889126e84fe742 Add post support to HTTP client diff -r d81de309a51f -r 729dc894e61c modules/http.tp --- a/modules/http.tp Sat Aug 10 15:51:31 2013 -0700 +++ b/modules/http.tp Sat Aug 10 18:26:14 2013 -0700 @@ -73,38 +73,46 @@ } } } + _handleResponse <- :sock { + resp <- "" + waiting <- true + headerText <- "" + rest <- "" + status <- "" + while: { waiting } do: { + data <- sock recv 4096 + resp <- resp . data + pos <- resp find: "\r\n\r\n" else: { -1 } + if: pos >= 0 { + waiting <- false + statusEnd <- resp find: "\r\n" else: { 0 } + statusStart <- (resp find: " " else: { 0 }) + 1 + status <- resp from: statusStart withLength: (statusEnd - statusStart) + headerText <- resp from: statusEnd + 2 withLength: pos - (statusEnd + 2) + rest <- resp from: pos + 4 + } + } + headers <- (headerText splitOn: "\r\n") fold: (dict linear) with: :acc curLine{ + //TODO: support multiple headers with the same name + part <- curLine partitionOn: ":" + acc set: (trim: (part before)) (trim: (part after)) + } + + response: headers status sock rest + } #{ client:usingPort <- :address :port{ #{ get <- :path { sock <- socket connectTo: address onPort: port sock send: "GET " . path . " HTTP/1.1\r\nHost: " . address . "\r\n\r\n" - resp <- "" - waiting <- true - headerText <- "" - rest <- "" - status <- "" - while: { waiting } do: { - data <- sock recv 4096 - resp <- resp . data - pos <- resp find: "\r\n\r\n" else: { -1 } - if: pos >= 0 { - waiting <- false - statusEnd <- resp find: "\r\n" else: { 0 } - statusStart <- (resp find: " " else: { 0 }) + 1 - status <- resp from: statusStart withLength: (statusEnd - statusStart) - headerText <- resp from: statusEnd + 2 withLength: pos - (statusEnd + 2) - rest <- resp from: pos + 4 - } - } - headers <- (headerText splitOn: "\r\n") fold: (dict linear) with: :acc curLine{ - //TODO: support multiple headers with the same name - part <- curLine partitionOn: ":" - acc set: (trim: (part before)) (trim: (part after)) - } - - - response: headers status sock rest + _handleResponse: sock + } + post:toPath:withType <- :body :path :type { + sock <- socket connectTo: address onPort: port + sock send: "POST " . path . " HTTP/1.1\r\nHost: " . address . "\r\nContent-Type: " . type . "\r\nContent-Length: " . (string: (body byte_length)) . "\r\n\r\n" + sock send: body + _handleResponse: sock } } }