Skip to content
Snippets Groups Projects
Commit 1002281d authored by Bernhard Posselt's avatar Bernhard Posselt
Browse files

handle http accept headers more gracefully

parent 077a542d
No related branches found
No related tags found
No related merge requests found
......@@ -162,15 +162,8 @@ class Dispatcher {
// if none is given try the first Accept header
if($format === null) {
$header = $this->request->getHeader('Accept');
$formats = explode(',', $header);
if($header !== null && count($formats) > 0) {
$accept = strtolower(trim($formats[0]));
$format = str_replace('application/', '', $accept);
} else {
$format = 'json';
}
$headers = $this->request->getHeader('Accept');
$format = $controller->getResponderByHTTPHeader($headers);
}
$response = $controller->buildResponse($response, $format);
......
......@@ -70,6 +70,30 @@ abstract class Controller {
}
/**
* Parses an HTTP accept header and returns the supported responder type
* @param string $acceptHeader
* @return string the responder type
*/
public function getResponderByHTTPHeader($acceptHeader) {
$headers = explode(',', $acceptHeader);
// return the first matching responder
foreach ($headers as $header) {
$header = trim($header);
$responder = str_replace('application/', '', $header);
if (array_key_exists($responder, $this->responders)) {
return $responder;
}
}
// no matching header defaults to json
return 'json';
}
/**
* Registers a formatter for a type
* @param string $format
......
......@@ -30,6 +30,14 @@ use OCP\AppFramework\Http\JSONResponse;
class ChildController extends Controller {
public function __construct($appName, $request) {
parent::__construct($appName, $request);
$this->registerResponder('tom', function ($respone) {
return 'hi';
});
}
public function custom($in) {
$this->registerResponder('json', function ($response) {
return new JSONResponse(array(strlen($response)));
......@@ -161,5 +169,20 @@ class ControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testDefaultResponderToJSON() {
$responder = $this->controller->getResponderByHTTPHeader('*/*');
$this->assertEquals('json', $responder);
}
public function testResponderAcceptHeaderParsed() {
$responder = $this->controller->getResponderByHTTPHeader(
'*/*, application/tom, application/json'
);
$this->assertEquals('tom', $responder);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment