Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Add just enough to make a request, but we just pass the response back…
… raw
- Loading branch information
Showing
with
71 additions
and 0 deletions.
- +34 −0 index.js
- +3 −0 package.json
- +34 −0 test.js
@@ -0,0 +1,34 @@ | ||
var net = require('net'); | ||
// Because we're building HTTP on top of raw TCP | ||
|
||
var url = require('url'); | ||
// We need to parse URLs into their parts -- the host and port and path are most interesting. | ||
|
||
module.exports = { | ||
request: function (uri, method, body) { | ||
var u = url.parse(uri); | ||
|
||
var c = net.createConnection({ host: u.hostname, port: u.port || 80 }); // No https for us! It's complicated. | ||
|
||
// The minimal HTTP/1.1 request: | ||
// GET / HTTP/1.1 | ||
// Host: foo.com | ||
// <this line blank> | ||
c.write(method + " " + u.path + " HTTP/1.1\r\n"); | ||
c.write("Host: " + u.host + "\r\n"); | ||
// We could write request headers here. Eventually we could create an interface for that. | ||
c.write("\r\n"); // End of header -- a blank line. | ||
|
||
if (method == 'HEAD' || method == 'GET') { | ||
// HEAD is just like GET, only the client tells the server they don't want the data, just the metadata. | ||
// Web crawlers use it to make the check if something is fresh cheap, sometimes. | ||
c.end(); | ||
} else { | ||
c.end(body); | ||
} | ||
|
||
// Just passing back c, raw, with whatever the server sends isn't a good interface but it's enough for now. | ||
return c; | ||
|
||
} | ||
} |
@@ -1 +1,35 @@ | ||
// tap is our test harness | ||
var tap = require('tap'); | ||
|
||
// We use the node http module to create a server to use while testing | ||
var http = require('http'); | ||
|
||
// bl = "buffer list" -- it's a stream sink, it collects everything the | ||
// stream emits as a pile of buffers, and gives it to you in one chunk | ||
// at the end. Great module. | ||
var bl = require('bl'); | ||
|
||
// client is the library we're making, the subject under test | ||
var client = require('./'); | ||
|
||
tap.test('the library loads a thing', function (t) { | ||
t.ok(client); | ||
t.equal(typeof client.request, 'function'); | ||
t.end(); | ||
}); | ||
|
||
tap.test('makes a simple GET request', function (t) { | ||
var server = http.createServer(function (req, res) { | ||
t.pass('Got request'); | ||
t.equal(req.url, '/'); | ||
res.end('Hello'); | ||
server.close(); | ||
}).listen(0, function () { // 0 means "Hey, Operating system! Assign us any free port!" | ||
var res = client.request("http://localhost:" + server.address().port + "/", 'GET'); | ||
res.pipe(bl(function (err, data) { | ||
t.error(err); | ||
t.ok(data); | ||
t.end(); | ||
})); | ||
}); | ||
}); |