Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/src/content/docs/basics/static-files.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,23 @@ Future<HttpServer> run(Handler handler, InternetAddress ip, int port) {

In the above example, we're using `api/static` as our static file directory but
you can specify a path to any directory for Dart Frog to use.

You can also serve a default document by specifying the `defaultDocument`
parameter when creating the `createStaticFileHandler` handler.

```dart
import 'dart:io';

import 'package:dart_frog/dart_frog.dart';

Future<HttpServer> run(Handler handler, InternetAddress ip, int port) {
const customStaticFilePath = 'api/static';
final cascade = Cascade()
.add(createStaticFileHandler(path: customStaticFilePath, defaultDocument: 'index.html'))
.add(handler);
return serve(cascade.handler, ip, port);
}
```

In this example, requests made to the root of the server will serve the
`index.html` file.
9 changes: 7 additions & 2 deletions packages/dart_frog/lib/src/create_static_file_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import 'package:shelf_static/shelf_static.dart';

/// Creates a [Handler] that serves static files within provided [path].
/// Defaults to the `public` directory.
Handler createStaticFileHandler({String path = 'public'}) {
return fromShelfHandler(createStaticHandler(path));
Handler createStaticFileHandler({
String path = 'public',
String? defaultDocument,
}) {
return fromShelfHandler(
createStaticHandler(path, defaultDocument: defaultDocument),
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,39 @@ void main() {
);
expect(notFoundResponse.statusCode, equals(HttpStatus.notFound));

final rootResponse = await http.get(
Uri.parse('http://localhost:$port/'),
);
expect(rootResponse.statusCode, equals(HttpStatus.notFound));

await server.close();
tempDir.delete(recursive: true).ignore();
});

test('serves default document', () async {
const port = 3003;
final tempDir = Directory.systemTemp.createTempSync();

const messageContents = 'hello world';
File(
path.join(tempDir.path, 'message.txt'),
).writeAsStringSync(messageContents);

final server = await serve(
createStaticFileHandler(
path: tempDir.path,
defaultDocument: 'message.txt',
),
'localhost',
port,
);

final messageResponse = await http.get(
Uri.parse('http://localhost:$port/'),
);
expect(messageResponse.statusCode, equals(HttpStatus.ok));
expect(messageResponse.body, equals(messageContents));

await server.close();
tempDir.delete(recursive: true).ignore();
});
Expand Down