Harbor as HTTP server

The harbor server can be used as a HTTP server. You can use the function harbor.http.register to register HTTP handlers. Its parameters are are follow:

harbor.http.register(port=8080,method="GET",uri,handler) where:

  • port is the port where to receive incoming connections
  • method is for the http method (or verb), one of: "GET", "PUT", "POST", "DELETE", "OPTIONS" and "HEAD"
  • uri is used to match requested uri. Perl regular expressions are accepted.
  • handler is the function used to process requests.

handler function has type:

(~protocol:string, ~data:string, 
 ~headers:[(string*string)], string)->string))->unit

where:

  • protocol is the HTTP protocol used by the client. Currently, one of "HTTP/1.0" or "HTTP/1.1"
  • data is the data passed during a POST request
  • headers is the list of HTTP headers sent by the client
  • string is the (unparsed) uri requested by the client, e.g.: "/foo?var=bar"

The handler function returns HTTP and HTML data to be sent to the client, for instance:

HTTP/1.1 200 OK\r\n\
Content-type: text/html\r\n\
Content-Length: 35\r\n\
\r\n\
<html><body>It works!</body></html>

(\r\n should always be used for line return in HTTP content)

For convenience, a http_response function is provided to create a HTTP response string. It has the following type:

(?protocol:string,?code:int,?headers:[(string*string)],
 ?data:string)->string

where:

  • protocol is the HTTP protocol of the response (default HTTP/1.1)
  • code is the response code (default 200)
  • headers is the response headers. It defaults to [] but an appropriate "Content-Length" header is added if not set by the user and data is not empty.
  • data is an optional response data (default "")

Thess functions can be used to create your own HTTP interface. Some examples are:

Redirect Icecast's pages

Some source clients using the harbor may also request pages that are served by an icecast server, for instance listeners statistics. In this case, you can register the following handler:

# Redirect all files other
# than /admin.* to icecast,
# located at localhost:8000
def redirect_icecast(~protocol,~data,~headers,uri) =
   http_response(
     protocol=protocol,
     code=301,
     headers=[("Location","http://localho