通过删除' next'简化Kitura RouterHandler。关闭?

时间:2017-02-11 13:51:16

标签: swift webserver kitura

我和Kitura一起玩。我安装了一个类似于:

的路由器端点
$dir = './archive/';
$zip_file = 'All-file.zip';

// Get real path for our folder
$rootPath = realpath($dir);

// Initialize archive object
$zip = new ZipArchive(); 
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file){
    // Skip directories (they would be added automatically)
    if (!$file->isDir()){
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();

header('Content-Description: File Transfer'); 
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);

我对这个let router = Router() router.all() { _, response, next in response.headers["Content-Type"] = "application/json; charset=utf-8" next() } router.get("/hello") { _, response, next in response.send("{\"message\": \"Hello World\"}") next() } Kitura.addHTTPServer(onPort: 9143, with: router) print("Application Server Starting...") Kitura.run() 闭包/回调参数感到非常困惑/沮丧。许多(可能是过时的?)教程都没有提及或包含它,但如果我不打电话,我的路由器会挂起,客户端响应永远不会被发送。

我有办法避免在next中拨打此电话吗?还是自动调用?在每种方法中需要手动执行此回调似乎是潜在的人为错误的巨大根源,并且它增加了混乱。 (像Spring Web这样的其他框架会自动执行链接,不需要RouterHandler调用。)

1 个答案:

答案 0 :(得分:3)

您可以在发送回复后致电response.end(),在这种情况下,您不需要拨打下一个()。 next()用于提供灵活性,因此可以根据需要调用或跳过后续处理程序。

但是你提出了一个好点,除非明确设置一个标志来跳过后续的处理程序,否则自动调用next()会更直观,我们会调查它。谢谢!

在查看代码时,看起来Kitura的后备处理(如果没有任何处理程序调用它会调用response.end())依赖于被调用的next(),它真的不应该。我会做出改变以解决这个问题。再次感谢您提出这一点。