1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-25 02:22:57 +01:00
guzzle/tests/server.js

147 lines
4.8 KiB
JavaScript
Raw Normal View History

/**
* Guzzle node.js test server to return queued responses to HTTP requests and
2011-03-03 12:24:51 -06:00
* expose a RESTful API for enqueueing responses and retrieving the requests
* that have been received.
*
* - Delete all requests that have been received:
* DELETE /guzzle-server/requests
* Host: 127.0.0.1:8125
*
* - Enqueue responses
* PUT /guzzle-server/responses
* Host: 127.0.0.1:8125
*
* [{ "statusCode": 200, "reasonPhrase": "OK", "headers": {}, "body": "" }]
*
* - Get the received requests
* GET /guzzle-server/requests
* Host: 127.0.0.1:8125
*
* - Shutdown the server
* DELETE /guzzle-server
* Host: 127.0.0.1:8125
*
* @package Guzzle PHP <http://www.guzzlephp.org>
* @license See the LICENSE file that was distributed with this source code.
*/
var http = require("http");
/**
* Guzzle node.js server
* @class
*/
var GuzzleServer = function(port, log) {
this.port = port;
this.log = log;
this.responses = [];
this.requests = [];
var that = this;
var controlRequest = function(request, req, res) {
if (req.url == '/guzzle-server/perf') {
res.writeHead(200, "OK", {"Content-Length": 16});
res.end("Body of response");
} else if (req.method == "DELETE") {
if (req.url == "/guzzle-server/requests") {
// Clear the received requests
that.requests = [];
res.writeHead(200, "OK", { "Content-Length": 0 });
res.end();
Guzzle 2.0 Adopting composer for dependency management Updating LICENSE, travis build file, making better use of git ignores, and remove unused build target Removing @author tags. Use the commit history for a changelog. Moving files from build folder to / Adding min build target to product a Guzzle only phar with no autoloader [Common] Accepting ZF1 or ZF2 cache in ZendCacheAdapter [Common] Optimizing Stream wrapper and EntityBody abstractions. [Common] [Http] Migrating from Guzzle event system to the Symfony2 event dispatcher [Common] Moved Inflector and Inspector to Service namespace [Http] Simplifying Guzzle\Guzzle curl detection [Http] Removing Guzzle\Http\Pool and now using Guzzle\Http\Curl\CurlMulti [Http] The helper methods from Guzzle\Http\Message\RequestFactory have been removed to prevent confusion and encourage developers to use Guzzle\Http\Client to create requests. [Http] Clients can now send one or more requests in an array using the send() method, so the batch() method was removed. [Http] Updating curl multi to allow blocking calls while sending other transfers [Http] Making the Request::hasHeader method more intuitive. Guzzle\Http\Message\AbstractMessage::hasHeader() now returns true if the header is found using exact matching. If the header is found using a regex or case-insensitive match, then it will return the name of the found header. [Http] Removing content-type guessing from EntityBody based on file extension and solely using finfo. [Http] Adding basic auth plugin [Http] Cleaning up CookieJar and CurlMulti [Http] Removing custom rawurlencode from QueryString because PHP 5.3 now properly deals with tilde characters. [Http] Minor optimization to parsing messages in RequestFactory [Http] Adding Guzzle\Http\Client for developers that don't need commands or service descriptions [Http] Making it easier to set a global User-Agent header for a Guzzle\Http\Client [Http] Fixing the discrepancies between the ClientInterface and Guzzle\Http\Client [Http] Adding the ability to set and retrieve tokenized headers from Requests and Responses [Service] Ditching NIH filters and using the Symfony2 validator [Service] Moving most service building logic to the ServiceBuilder::factory method so that it is easier to build custom config readers. [Service] Allowing deep nested command inheritance. [Service] Cleaning up Inflector caching. [Service] Getting rid of concept of can_batch because everything is now sent in parallel. [Service] Adding a JSON description builder. [Service] Cleaning up ResourceIteratorApplyBatched. [Service] Removing caching stuff from ServiceBuilder because the data being cached is extremely fast to generate. [Service] Added a method to serialize the ServiceDescription in case a ServiceDescription needs to be cached in an application. [Service] Making description builders use static methods. [Service] Adding support to include other description files for XML and JSON description builders. [Service] Adding support for filters to ApiCommands [Service] Using {{}} instead of $. to reference other services as a dependency for another service
2012-01-14 13:57:05 -06:00
if (this.log) {
console.log("Flushing requests");
}
} else if (req.url == "/guzzle-server") {
// Shutdown the server
res.writeHead(200, "OK", { "Content-Length": 0, "Connection": "close" });
res.end();
if (this.log) {
console.log("Shutting down");
}
that.server.close();
}
} else if (req.method == "GET") {
if (req.url === "/guzzle-server/requests") {
// Get received requests
var data = that.requests.join("\n----[request]\n");
res.writeHead(200, "OK", { "Content-Length": data.length });
res.end(data);
Changes to support a Guzzle\Http\Parser namespace [Common] Adding keySearch method to Collection [Http] Moving POST curl option logic from EntityEnclosingRequest to the curl factory method Directly using the HTTP request object when creating curl handles in the factory method No longer adding a read callback when sending POSTs through CURLOPT_POSTFIELDS In an effort to mitigate random segfaults and bus errors, using a queue for removing curl and close handles from a multi object so that they are only removed when the multi handle has finished sending all requests. Calling reset() each time a curl multi handle has finished all requests. EntityEnclosingRequest::getPostFields() now returns a Collection object Simplifying the EntityEnclosingRequest::getPostFiles method Adding an array cache to header objects Moving the header comparison DSL from the Tests namespace to Guzzle\Http\Message\HeaderComparison, and adding tests. Adding message, cookie, and url parser interfaces and default implementations. Using a parser registry to manage globally registered parsers. Removing parsing from Response and RequestFactory. Renaming protocol_version to version Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. Simplifying the chunked encoding handling in RequestFactory Moving cookie parsing out of the cookie plugin and into Guzzle\Http\Parser\Cookie\CookieParser Removing regexps from the cookie parser and simply using stripos Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. Adding more logging to node.js test webserver Adding pecl_http message parser. Installing pecl when travis boots up
2012-05-10 21:30:09 -07:00
if (that.log) {
Guzzle 2.0 Adopting composer for dependency management Updating LICENSE, travis build file, making better use of git ignores, and remove unused build target Removing @author tags. Use the commit history for a changelog. Moving files from build folder to / Adding min build target to product a Guzzle only phar with no autoloader [Common] Accepting ZF1 or ZF2 cache in ZendCacheAdapter [Common] Optimizing Stream wrapper and EntityBody abstractions. [Common] [Http] Migrating from Guzzle event system to the Symfony2 event dispatcher [Common] Moved Inflector and Inspector to Service namespace [Http] Simplifying Guzzle\Guzzle curl detection [Http] Removing Guzzle\Http\Pool and now using Guzzle\Http\Curl\CurlMulti [Http] The helper methods from Guzzle\Http\Message\RequestFactory have been removed to prevent confusion and encourage developers to use Guzzle\Http\Client to create requests. [Http] Clients can now send one or more requests in an array using the send() method, so the batch() method was removed. [Http] Updating curl multi to allow blocking calls while sending other transfers [Http] Making the Request::hasHeader method more intuitive. Guzzle\Http\Message\AbstractMessage::hasHeader() now returns true if the header is found using exact matching. If the header is found using a regex or case-insensitive match, then it will return the name of the found header. [Http] Removing content-type guessing from EntityBody based on file extension and solely using finfo. [Http] Adding basic auth plugin [Http] Cleaning up CookieJar and CurlMulti [Http] Removing custom rawurlencode from QueryString because PHP 5.3 now properly deals with tilde characters. [Http] Minor optimization to parsing messages in RequestFactory [Http] Adding Guzzle\Http\Client for developers that don't need commands or service descriptions [Http] Making it easier to set a global User-Agent header for a Guzzle\Http\Client [Http] Fixing the discrepancies between the ClientInterface and Guzzle\Http\Client [Http] Adding the ability to set and retrieve tokenized headers from Requests and Responses [Service] Ditching NIH filters and using the Symfony2 validator [Service] Moving most service building logic to the ServiceBuilder::factory method so that it is easier to build custom config readers. [Service] Allowing deep nested command inheritance. [Service] Cleaning up Inflector caching. [Service] Getting rid of concept of can_batch because everything is now sent in parallel. [Service] Adding a JSON description builder. [Service] Cleaning up ResourceIteratorApplyBatched. [Service] Removing caching stuff from ServiceBuilder because the data being cached is extremely fast to generate. [Service] Added a method to serialize the ServiceDescription in case a ServiceDescription needs to be cached in an application. [Service] Making description builders use static methods. [Service] Adding support to include other description files for XML and JSON description builders. [Service] Adding support for filters to ApiCommands [Service] Using {{}} instead of $. to reference other services as a dependency for another service
2012-01-14 13:57:05 -06:00
console.log("Sending receiving requests");
}
}
} else if (req.method == "PUT") {
if (req.url == "/guzzle-server/responses") {
Changes to support a Guzzle\Http\Parser namespace [Common] Adding keySearch method to Collection [Http] Moving POST curl option logic from EntityEnclosingRequest to the curl factory method Directly using the HTTP request object when creating curl handles in the factory method No longer adding a read callback when sending POSTs through CURLOPT_POSTFIELDS In an effort to mitigate random segfaults and bus errors, using a queue for removing curl and close handles from a multi object so that they are only removed when the multi handle has finished sending all requests. Calling reset() each time a curl multi handle has finished all requests. EntityEnclosingRequest::getPostFields() now returns a Collection object Simplifying the EntityEnclosingRequest::getPostFiles method Adding an array cache to header objects Moving the header comparison DSL from the Tests namespace to Guzzle\Http\Message\HeaderComparison, and adding tests. Adding message, cookie, and url parser interfaces and default implementations. Using a parser registry to manage globally registered parsers. Removing parsing from Response and RequestFactory. Renaming protocol_version to version Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. Simplifying the chunked encoding handling in RequestFactory Moving cookie parsing out of the cookie plugin and into Guzzle\Http\Parser\Cookie\CookieParser Removing regexps from the cookie parser and simply using stripos Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. Adding more logging to node.js test webserver Adding pecl_http message parser. Installing pecl when travis boots up
2012-05-10 21:30:09 -07:00
if (that.log) {
console.log("Adding responses...");
}
// Received response to queue
Changes to support a Guzzle\Http\Parser namespace [Common] Adding keySearch method to Collection [Http] Moving POST curl option logic from EntityEnclosingRequest to the curl factory method Directly using the HTTP request object when creating curl handles in the factory method No longer adding a read callback when sending POSTs through CURLOPT_POSTFIELDS In an effort to mitigate random segfaults and bus errors, using a queue for removing curl and close handles from a multi object so that they are only removed when the multi handle has finished sending all requests. Calling reset() each time a curl multi handle has finished all requests. EntityEnclosingRequest::getPostFields() now returns a Collection object Simplifying the EntityEnclosingRequest::getPostFiles method Adding an array cache to header objects Moving the header comparison DSL from the Tests namespace to Guzzle\Http\Message\HeaderComparison, and adding tests. Adding message, cookie, and url parser interfaces and default implementations. Using a parser registry to manage globally registered parsers. Removing parsing from Response and RequestFactory. Renaming protocol_version to version Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. Simplifying the chunked encoding handling in RequestFactory Moving cookie parsing out of the cookie plugin and into Guzzle\Http\Parser\Cookie\CookieParser Removing regexps from the cookie parser and simply using stripos Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. Adding more logging to node.js test webserver Adding pecl_http message parser. Installing pecl when travis boots up
2012-05-10 21:30:09 -07:00
var data = request.split("\r\n\r\n")[1];
if (!data) {
if (that.log) {
console.log("No response data was provided");
}
res.writeHead(400, "NO RESPONSES IN REQUEST", { "Content-Length": 0 });
Changes to support a Guzzle\Http\Parser namespace [Common] Adding keySearch method to Collection [Http] Moving POST curl option logic from EntityEnclosingRequest to the curl factory method Directly using the HTTP request object when creating curl handles in the factory method No longer adding a read callback when sending POSTs through CURLOPT_POSTFIELDS In an effort to mitigate random segfaults and bus errors, using a queue for removing curl and close handles from a multi object so that they are only removed when the multi handle has finished sending all requests. Calling reset() each time a curl multi handle has finished all requests. EntityEnclosingRequest::getPostFields() now returns a Collection object Simplifying the EntityEnclosingRequest::getPostFiles method Adding an array cache to header objects Moving the header comparison DSL from the Tests namespace to Guzzle\Http\Message\HeaderComparison, and adding tests. Adding message, cookie, and url parser interfaces and default implementations. Using a parser registry to manage globally registered parsers. Removing parsing from Response and RequestFactory. Renaming protocol_version to version Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. Simplifying the chunked encoding handling in RequestFactory Moving cookie parsing out of the cookie plugin and into Guzzle\Http\Parser\Cookie\CookieParser Removing regexps from the cookie parser and simply using stripos Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. Adding more logging to node.js test webserver Adding pecl_http message parser. Installing pecl when travis boots up
2012-05-10 21:30:09 -07:00
} else {
that.responses = eval("(" + data + ")");
if (that.log) {
console.log(that.responses);
}
res.writeHead(200, "OK", { "Content-Length": 0 });
}
res.end();
}
}
};
var receivedRequest = function(request, req, res) {
if (req.url.indexOf("/guzzle-server") === 0) {
controlRequest(request, req, res);
} else if (req.url.indexOf("/guzzle-server") == -1 && !that.responses.length) {
res.writeHead(500);
res.end("No responses in queue");
} else {
var response = that.responses.shift();
res.writeHead(response.statusCode, response.reasonPhrase, response.headers);
res.end(response.body);
that.requests.push(request);
}
};
this.start = function() {
that.server = http.createServer(function(req, res) {
var request = req.method + " " + req.url + " HTTP/" + req.httpVersion + "\r\n";
for (var i in req.headers) {
request += i + ": " + req.headers[i] + "\r\n";
}
request += "\r\n";
// Receive each chunk of the request body
req.addListener("data", function(chunk) {
request += chunk;
});
// Called when the request completes
req.addListener("end", function() {
receivedRequest(request, req, res);
});
});
that.server.listen(port, "127.0.0.1");
if (this.log) {
console.log("Server running at http://127.0.0.1:8125/");
}
};
};
// Get the port from the arguments
port = process.argv.length >= 3 ? process.argv[2] : 8125;
log = process.argv.length >= 4 ? process.argv[3] : false;
// Start the server
server = new GuzzleServer(port, log);
Breaking / Potentially breaking changes: 1. Adopting a marker interface for Guzzle exceptions. A. All exceptions emitted from Guzzle are now wrapped with a Guzzle namespaced exception. B. Guzzle\Common\GuzzleExceptionInterface was renamed to Guzzle\Common\GuzzleException C. Guzzle\Common\ExceptionCollection was renamed to Guzzle\Common\Exception\ExceptionCollection 2. Using Header objects for Request and Response objects A. When you call $request->getHeader('X'), you will get back a Guzzle\Http\Message\Header object that contains all of the headers that case insensitively match. This object can be cast to a string or iterated like an array. You can pass true in the second argument to retrieve the header as a string. B. Removing the old Guzzle\Common\Collection based searching arguments from most of the request and response header methods. All retrievals are case-insensitive and return Header objects. 3. Changing the two headers added by the cache plugin to just one header with key and ttl. 4. Changing Guzzle\Http\Message\Response::factory() to fromMessage(). 5. Removing the NullObject return value from ServiceDescriptions and instead simply returning null New Features / enhancements: 1. Adding Guzzle\Http\Message\AbstractMessage::addHeaders() 2. Making it simpler to create service descriptions using a unified factory method that delegates to other factories. 3. Better handling of ports and hosts in Guzzle\Http\Url Note: This is a noisy diff because I'm removing trailing whitespace and adding a new line at the end of each source file.
2012-04-21 00:23:07 -07:00
server.start();