Headers 基于 Slim 3 的路由

Headers based routing with Slim 3

我有一条 Slim 3 路线:$app->get('/calendar/{date}', 'CalendarCtrl:getSchedule');
此路线可以 return 相同的时间表,通过简单的 HTML 列表,json 或 xml 格式。
现在我正在寻找一个基于 Accept(或更多 headers)HTTP header 的简单 REST 解决方案。

例如:
要求:

GET /calendar/2017-01-01  
Accept: application/json

回复:

Content-Type: application/json
Body: {json schedule}

所以路线应该是这样的:$app->get('/calendar/{date}', {Accept: application/json}, 'CalendarCtrl:getScheduleJson');

我知道我可以在路由处理程序中检查 header。但我正在寻找一个简单的声明式解决方案。

在发送来自您的 API

的响应之前,添加一个中间件来检查 header
$app->add(function ($req, $res, $next) {
//Checking for $req content-type here then send the response with the same one 
//example 
$headerValue= $req->getHeader('Accept');
if($headerValue=='application/json')
{
  $response = $next($req, $res);
    return $response
            ->withHeader('Content-type', 'application/json');
 }
else{

//check for other header here  
}      
});