Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Serving files with http_server


One of the main functions of a web server that we take for granted is the serving of static files. We can write this functionality completely with the classes from dart:io, but the Dart team has written a pub package called http_server with the aim to simplify web server programming to provide web content. We will use http_server in this recipe to code a web server that serves files. You can find the code in the project serving_files.

How to do it...

Perform the following steps to construct a web server for server files:

  1. In the first example, serving_file.dart, you see the code for a web server delivering a file called Learning Dart Packt Publishing.html:

    import 'dart:io';
    import 'package:http_server/http_server.dart';
    
    InternetAddress HOST = InternetAddress.LOOPBACK_IP_V6;
    const PORT = 8080;
    
    void main() {
      VirtualDirectory staticFiles = new VirtualDirectory('.');
      HttpServer.bind(HOST, PORT).then((server) {
        server.listen((req) {
        staticFiles.serveFile...