dart-archive / shelf_static

archived repo
https://github.com/dart-lang/shelf/tree/master/pkgs/shelf_static
BSD 3-Clause "New" or "Revised" License
24 stars 24 forks source link

Problems caused by closures #60

Open mengyanshou opened 3 years ago

mengyanshou commented 3 years ago
Handler createFileHandler(String path, {String? url, String? contentType}) {
  final file = File(path);
  if (!file.existsSync()) {
    throw ArgumentError.value(path, 'path', 'does not exist.');
  } else if (url != null && !p.url.isRelative(url)) {
    throw ArgumentError.value(url, 'url', 'must be relative.');
  }

  final mimeType = contentType ?? _defaultMimeTypeResolver.lookup(path);
  url ??= p.toUri(p.basename(path)).toString();

  return (request) {
    if (request.url.path != url) return Response.notFound('Not Found');
    return _handleFile(request, file, () => mimeType);
  };
}

this function reture closure,and i tried call this funtion twice,the second time in this closure,the url still is the first time passed in.

kevmoo commented 3 years ago

@Nightmare-MY – would you provide a code sample that demonstrates this behavior?

mengyanshou commented 3 years ago

add a print in createFileHandler

Handler createFileHandler(String path, {String? url, String? contentType}) {
  final file = File(path);
  if (!file.existsSync()) {
    throw ArgumentError.value(path, 'path', 'does not exist.');
  } else if (url != null && !p.url.isRelative(url)) {
    throw ArgumentError.value(url, 'url', 'must be relative.');
  }

  final mimeType = contentType ?? _defaultMimeTypeResolver.lookup(path);
  url ??= p.toUri(p.basename(path)).toString();

  return (request) {
    print('url -> $url');
    if (request.url.path != url) return Response.notFound('Not Found');
    return _handleFile(request, file, () => mimeType);
  };
}

and exec this code in example

  final handler1 = createFileHandler('example/files/dart.png');

  final handler2 = createFileHandler('example/files/index.html');
  io.serve(handler1, 'localhost', 8000, shared: true);
  io.serve(handler2, 'localhost', 8000, shared: true);

and i can request http://localhost:8000/dart.png to get a image but i can't get http://localhost:8000/index.html to get html when i send get request to http://localhost:8000/index.html the print is url -> dart.png

kevmoo commented 3 years ago

CC @natebosch – that IS weird