douyaosi3164 2017-04-12 17:26
浏览 39
已采纳

基于标题的路由与Slim 3

I have a Slim 3 route: $app->get('/calendar/{date}', 'CalendarCtrl:getSchedule');
This route can return the same schedule by simple HTML list, json or xml format.
Now I'm looking for a simple REST solution based on Accept (or more headers) HTTP header.

For example:
Request:

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

Response:

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

So a route should be smth like this: $app->get('/calendar/{date}', {Accept: application/json}, 'CalendarCtrl:getScheduleJson');

I know I can check for that header in a route handler. But I'm looking for a simple declarative solution.

  • 写回答

1条回答 默认 最新

  • dtwupu6414 2017-04-13 11:56
    关注

    Add a middleware to check for that header before sending the response from your API

    $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  
    }      
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?