2015-11-08 277 views
1

我正在尋找有關如何改進此文件服務器的指導。在Dart服務器上適當使用「路由」和「路徑」庫

目前它無法處理POST,因爲每個請求都被傳遞到http_server庫。它也天真地路由URL;可以用Router s來改善嗎?也許path lib也可以提供幫助?

import 'dart:io'; 
import 'package:http_server/http_server.dart'; 

// TODO: use these imports :) 
import 'package:path/path.dart' as path; 
import 'package:route/url_pattern.dart'; 

final address = InternetAddress.LOOPBACK_IP_V4; 
const port = 4040; 

final buildPath = Platform.script.resolve('web'); 
final publicDir = new VirtualDirectory(buildPath.toFilePath()); 

main() async { 
    // Override directory listing 
    publicDir 
    ..allowDirectoryListing = true 
    ..directoryHandler = handleDir 
    ..errorPageHandler = handleError; 

    // Start the server 
    final server = await HttpServer.bind(address, port); 
    print('Listening on port $port...'); 
    await server.forEach(publicDir.serveRequest); 
} 

// Handle directory requests 
handleDir(dir, req) async { 
    var indexUri = new Uri.file(dir.path).resolve('index.html'); 
    var index = new File.fromUri(indexUri); 
    if (!await index.exists()) { 
    handleError(req); 
    return; 
    } 
    publicDir.serveFile(index, req); 
} 

// Handle error responses 
handleError(req) { 
    req.response.statusCode = HttpStatus.NOT_FOUND; 
    var errorUri = new Uri.directory(publicDir.root).resolve('error.html'); 
    var errorPage = new File.fromUri(errorUri); 
    publicDir.serveFile(errorPage, req); 
} 

回答

1

我沒有看到解決這個

await for (var req in server) { 
    // distribute requests to different handlers 
    if(req.method == 'POST') { 

    } else { 
    publicDir.serveRequest(req); 
    } 
} 

的方式或者你可以使用shelfshelf_routeshelf_static它允許您指定的請求和處理程序更聲明的風格,但該做的罩

https://pub.dartlang.org/search?q=shelf_static

+0

感謝您提到貨架,我會看看 – Ganymede

+0

有關'path'包的問題,​​請添加更具體的問題。我沒有使用帶有uris的'path'包,只使用文件路徑,但它非常簡單,只能在字符串上運行。 –

+0

真棒,只是我正在尋找的建議。我知道我的問題是模糊的:) – Ganymede

0

shelf_static下相同非常適合文件服務器,並且具有路由的服務器可以使用shelf_route完成。

import 'dart:io'; 

import 'package:shelf_io/shelf_io.dart' as io; 
import 'package:shelf_static/shelf_static.dart'; 
import 'package:path/path.dart' show join, dirname; 

final address = InternetAddress.LOOPBACK_IP_V4; 
const port = 8080; 

main() async { 
    var staticPath = join(dirname(Platform.script.toFilePath()), '..', 'web'); 
    var staticHandler = createStaticHandler(staticPath, defaultDocument: 'index.html'); 
    var server = await io.serve(staticHandler, address, port); 
}