Giter VIP home page Giter VIP logo

shelf_static's Introduction

shelf_static's People

Contributors

abarth avatar athomas avatar bcko avatar dantup avatar devoncarew avatar franklinyow avatar grouma avatar jakemac53 avatar kevmoo avatar lrhn avatar mengyanshou avatar natebosch avatar nex3 avatar sanmadjack avatar sethladd avatar srawlins avatar whesse avatar xvrh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

shelf_static's Issues

Default document for directory does not work when using shelf_route

import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_route/shelf_route.dart' as route;
import 'package:shelf_static/shelf_static.dart' as static;

void main() {

  var staticHandler = static.createStaticHandler('static_content', defaultDocument: 'index.html');
  final routerHandler = (
      route.router()
        ..get('/foo', staticHandler)
        ..get('/', _echoRequest)
  ).handler;

  io.serve(routerHandler, '0.0.0.0', 8080).then((server) {
    print('Serving at http://${server.address.host}:${server.port}');
  });

}

shelf.Response _echoRequest(shelf.Request request) {
  return new shelf.Response.ok('Request for "${request.url}"');
}

Run this and goto:

http://localhost:8080/foo/

Produces:

Internal Server Error

In console:

ERROR - 2014-11-17 09:58:22.921
Error thrown by handler.
'package:shelf_static/src/static_handler.dart': Failed assertion: line 73 pos 14: '!uri.path.endsWith('/')' is not true.
package:shelf_static/src/static_handler.dart 73:14  createStaticHandler.<fn>
package:shelf_route/shelf_route.dart 136:19         _Route.handle
package:shelf_route/shelf_route.dart 100:24         _handleRequest
dart:isolate                                        _RawReceivePortImpl._handleMessage

Expected to return "index.html" for /foo and run _echoRequest for other URLS.

Migrating to null safety

I was wondering if there are any plans to migrate this package to null safety?

I would be happy to have an attempt at null safety migration if there are not.

createStaticHandler not working on macOS (desktop) target

var staticHandler = createStaticHandler('path/path', defaultDocument: 'index.html');

does not work for macOS.

The error is:
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Invalid argument(s): A directory corresponding to fileSystemPath "path/path" could not be found

Problems caused by closures

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.

Tag v0.2.4

I see 0.2.4 on pub, but it's not tagged in GitHub. Can we tag this release?

Add option to Override Headers

I need to set ACCESS_CONTROL_ALLOW_ORIGIN: '*' because i got erros when try load .ttf fonts with static server.

I try to do with shelf_cors_headers but without success.

Can you add option to override Headers? Or can i do this with another way? If exist please let me know.

(feature) configure Cache-Control headers

For a directory or a regexp for filenames, I'd like to set Cache-Control headers. I mostly would like to say "resources of this type expire in XXXX time". I'd also want to set public/private, but might as well allow the user to set any of the Cache-Control variables.

'Not Found' Response for a file that is present when using createFileHandler

Handler createFileHandler in static_handler.dart, this line is stopping the file being sent :
if (request.url.path != url) return Response.notFound('Not Found');

if removed my code works fine and the file is served.

The path parameter is 'public/css/styles.css' (I've checked Directory.current and the path is correctly relative to it)
the request.url.path is 'css/styles.css'
url var is reduced to 'styles.css' via basename so then is not equal to request.url.path

Not sure if I'm miss using the function? (I'm new to Dart)

Here is my router function :

    router.get('/<file|.*>', (Request req) async {
      final assetPath = folderPath + '/' + req.requestedUri.path.substring(1);
      if (await io.File(assetPath).exists() == true) {
        return await createFileHandler(assetPath)(req);
      } else {
        return Response.notFound('');
      }
    });

(feature) configure gzip for resources

For some resources, like text resources, I'd like the serving infrastructure to compress on the fly. For other resources, like images, I do not want to compress on the fly.

Perhaps this configurability is in the domain of shelf_static?

feat(shelf_static): Add a template engine to inject values on static files

I haven't been able to find this feature but I'm willing to help with a PR if needed!


Imagine having this page in a file called index.html:

<html>
<body>
<p>Hello, my name is {:name} and I am {:my_age} years old</p>
</body>
</html>

I would like to be able to replace {:name} and {:my_age} with some values coming from Dart, like this:

final indexPageValues = PageValues(
  file: 'index.html',
  values: {
    'name': 'Alberto',
    'my_age': 25,
  },
);

shelf_static.createStaticHandler(
  'public', 
  defaultDocument: 'index.html',
 
  // add this param
  pageValues: <PageValues>[
    indexPageValues,
  ],
);

In this way, the {:some_name} tags in the HTML code will be replaced by the values provided via Dart. The result would be

<html>
<body>
<p>Hello, my name is Alberto and I am 25 years old</p>
</body>
</html>

This would also allow custom HTML processed from Dart.


Please take the the {:some_name} syntax as example, don't focus on it. Focus on the general idea instead: might this be good? 🙂 what could I improve to make this look better?

Thank you!

How is the default index page served

I'm trying to convert my current VirtualDirectory code to use shelf_static. I'm trying to figure out how to serve the default index.html file when the route is '/'. Thanks in advance.

Stale content is served on windows when browser sents IfModifiedSince header

On Windows, updating the file on disk and reloading in the browser returns a "Not modified" header, so stale content is shown.

I believe the cause is the user of stat.changed here:

https://github.com/dart-lang/shelf_static/blob/fb4506e7485e4ff7a3b97dfae3f6e02215e64782/lib/src/static_handler.dart#L185

The comment on stat.changed says:

  /**
   * The time of the last change to the data or metadata of the file system
   * object.
   *
   * On Windows platforms, this is instead the file creation time.
   */

I'm not sure why it has this behaviour on Windows, but there's another field called modified that doesn't contain this text, so perhaps that one should be used instead?

createFileHandler for video file

I've tried to use createFileHandler for video file.
and i can't buffer the video in the browser,It only plays when I download it completely.
but i use virtual_directory from httt_server work normally, i think maybe the reason is response doesn't containes content-range

Stop using scheduled_test

The scheduled_test package is no longer being maintained. shelf_static should switch to using test directly, probably along with the test_descriptor package.

[Question] Refused to apply style.

The html loads with no styles. and in inspection console it shows this

Refused to apply style from 'http://localhost:1031/assets/style.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

I found no solution and any resource. Hoping for the solution. as of the createStaticFileHandler function says MimeTypeResolver, I really don't understand it. please explain me(us in Docs too) about this.

api.dart

Future<void> main() async {
  /// Router object
  Router app = Router();
  app.get('/assets/<file | .*>',
      createStaticHandler('public', serveFilesOutsidePath: true));
  app.get('/', (Request request, String name) {
    console.log(name);
    String indexFile = File('public/index.html').readAsStringSync();
    return Response.ok(
      indexFile,
      headers: <String, Object>{'Content-Type': 'text/html'},
    );
  });

  /// Serving
  await shelf_io.serve(app, 'localhost', 1031).then((HttpServer value) =>
      console.log(
          'API running at http://${value.address.host}:${value.port} 🔥🔥🔥'));
}

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FlutterMatic</title>
    <link rel="stylesheet" type="text/css" href="./assets/styles.css" />
</head>

<body>
    <h1>Hello world</h1>
</body>

</html>

This is how I'm using it.

More dart2 const renames

Analyzing shelf_static...
hint • 'FILE' is deprecated and shouldn't be used at lib/src/static_handler.dart:73:44 • deprecated_member_use
hint • 'DIRECTORY' is deprecated and shouldn't be used at lib/src/static_handler.dart:75:51 • deprecated_member_use
hint • 'DIRECTORY' is deprecated and shouldn't be used at lib/src/static_handler.dart:100:44 • deprecated_member_use
3 hints found.

Problem with flutter web and HTTP request

I am using shelf_static to serve a Flutter web app that I'm developing and I'm trying to make it run on Windows desktop.
The Flutter desktop side is pretty simple: it's mostly taken from shelf usage examples, and the relevant part is this:

final _staticHandler = createStaticHandler(webAppFolder, defaultDocument: 'index.html');
final _router = shelf_router.Router()
      ..get(
        '/time',
        (request) => shelf.Response.ok(DateTime.now().toUtc().toIso8601String()),
      );

final cascade = shelf.Cascade()
    .add(_staticHandler)
    .add(_router);
logger.i("handler ready");

try {
  var server = await shelf_io.serve(
    cascade.handler,
    InternetAddress.anyIPv4,
    port,
    securityContext: secureContext,
  );
  server.autoCompress = true;

  logger.i("Serving at https://${server.address.host}:${server.port}");

The _staticHandler serves the webAppFolder in the same path, which contains the output of the Flutter web app, and everything seems to start up just fine: the initial page of the web app is available at the given address.
The problem arises when the web app performs a query to CouchDb to retrieve some data, so basically issues an HTTP GET request to an URL: the response received is correct, the only things that don't add up are the names of the root-level JSON properties. They are changed, compressed or obfuscated or something like that. I didn't notice it at first because when I debug directly the web app, everything is as expected, and the JSON properties keep their names. But, when served through shelf they change, and the web app fails to recognize the answers received by the HTTP GET. Here's an example of the difference.

Web App Shelf
"seq":false "error":false
"srT":200 "errorCode":200
"sq1":null "successText":null
"szK":null "successText":null
"syM":null "allResponseHeader":null
"stp":"GET" "method":"GET"
"sAX":"{"total_rows":7 "responseText":"{"total_rows":7
"offset":5 "offset":5
"rows":[\r\n{"id":"f42186d6d056b4013540f797a2000316" "rows":[\r\n{"id":"f42186d6d056b4013540f797a2000316"

... and so on. Notice that the internal JSON element isn't affected by this and fields like "total_rows" remain the same.

I am pretty new with HTTP GET and such, so maybe there's something obvious I'm missing, and I could probably work around this thing by using the properties order and not the name, but I would prefer avoiding this. Since I am struggling in finding help on the web for this particular setup, I'm resorting to create an issue.
It's worth noting that an HTTP GET performed by the desktop app itself before serving the web app does not have this issue: in that case, the property names are as unchanged as I expect them.

Filesystem

How can I use shelf_static to serve files in the internal storage of the device.

how do i use it with shelf_router

I tried the following:

  app.mount('/', createFileHandler('web/index.html'));

  app.mount('/web/<name|.*>', createStaticHandler('web'));

but i only get Not found.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.