Alice Project

The HttpServer structure

________ Synopsis ____________________________________________________

    signature HTTP_SERVER
    structure HttpServer : HTTP_SERVER

This structure provides a simple, extensible server for the HTTP/1.1 protocol as specified in RFC 2616.

See also: Url, Http, HttpClient, Socket

________ Import ______________________________________________________

    import structure HttpServer from "x-alice:/lib/system/HttpServer"
    import signature HTTP_SERVER from "x-alice:/lib/system/HTTP_SERVER-sig"

________ Interface ___________________________________________________

    signature HTTP_SERVER =
	type handler = Http.request -> Http.response

	val logOut : TextIO.outstream option ref
	val idleTime : Time.t ref

	val start : int option -> int
	val register : Url.t * handler -> unit

________ Description _________________________________________________

type handler = Http.request -> Http.response

The type of handlers for HTTP requests.


specifies a stream on which to write log messages about incoming connections and closed idle connections. The default is NONE.


specifies the length of time to allow persistent connections to be idle before they are closed. The default is 30 seconds.

start portOpt

starts a HTTP server and lets it listen for connections in a concurrent thread. If portOpt is SOME port, tries to listen on port, else selects an available port. Returns the port on which it listens for request.

register (url, handler)

registers handler for requests make to url. Only the path component or url is significant.

________ Examples ____________________________________________________

The following demonstrates how to start a simple HTTP server which interprets all requested URLs as files under a document root; it just returns the file with type text/plain. If the file could not be found, it returns a 404 Not Found response.

Download full source code

val documentRoot = "/tmp/httproot"

val notFoundDocument = "The requested document could not be found\n"

fun documentHandler (request: Http.request) =
	val relFile = Url.toString (Url.setQuery (#uri request, NONE))
	val file = TextIO.openIn (documentRoot ^ relFile)
	val body = TextIO.inputAll file
	TextIO.closeIn file;
	    {statusCode = 200, contentType = "text/plain", body}
    end handle IO.Io {...} =>
	    {statusCode = 404, contentType = "text/plain",
	     body = notFoundDocument}

val port = HttpServer.start NONE
val _ = HttpServer.register (Url.empty, documentHandler)
val _ = TextIO.print ("started server at port " ^
		      Int.toString port ^ "\n")

last modified 2007/Mar/30 17:10