finger exercises: http file server

In which I try to implement a simple http file server in Dart (using the existing http implementation in the standard library of course). My goal is to get something along the lines of the various one-line servers that exist for Ruby and Python.

Looking at the documentation I see a simple example to get started but it uses then to chain callbacks. Fortunately I know about async/await so I’m gonna use that because I think that looks nicer

I’m also using final because I want the compiler to complain if I reassign something I didn’t intend to reassign. This is just good code hygiene. Dart also has const but the restrictions on that require everything being available at compile-time and by the end of this I don’t expect to have many places where that might be useful so gonna stick with final for the time being.

Going through the motions to start the server and testing it I see the right response. Time to serve a specific file

Gonna save that as file.txt alongside the server code. Looking at the documentation I see there is a File class and like a lot of other core classes it uses Streams and Futures. After some false starts this is the code that seems to work

Now I want to see how I can pass in the name of the file. The documentation leads to uri getter on HttpRequest object which returns a Uri. The documentation for Uri has path and pathSegments which seem like they will do the trick. Gonna try path first

That leads to a dead end. It can be fixed but will save that for some other time. Onto pathSegments

That one works well enough but dies when there is no first element. Time to look into some error handling so that the server doesn’t crash whenever assumptions are violated

I don’t expect grabbing the response stream or closing it will throw any errors and if it does then in those cases I do want the server to crash because I can’t really imagine how to recover in those cases anyway. I’m gonna be a good citizen and set the status code to 400 in case I do catch any exceptions

Customizing the listening port, serving an index page and files deeper than one level deep are left as exercises for the reader.