package mehari

All checked builds pass
  1. Overview
  2. Docs
A library for building Gemini servers

Install

dune-project
 Dependency

Authors

Maintainers

Sources

0.5.tar.gz
md5=035934743b73b6b5a593d3146533b0b2
sha512=570071e2fadd19e396f8fe86162c75069761acbe5c3b2ab3791c7c30a543a174b7f65bf5ba73bf5842ad5b071faabab071db23c19275b8ee8673190af9007cff

doc/index.html

Mehari

Mehari is a cross-platform library for building Gemini servers. It fully implements the Gemini protocol specification. It offers a simple and clean interface to create complete Gemini web apps. It takes inspiration from Dream, a tidy, feature-complete Web framework.

Consult the Tutorial and examples.

Interface

Mehari provides several packages:

  • Mehari provides the core abstraction, it does not depend on any platform code, and does not interact with the environment.

Tutorial

Respond to request

The first form of abstraction is the Mehari.handler which is essentially an asynchronous function from Mehari.request to Mehari.response. This is the simplest possible handler that responds to all requests in the same way:

(fun req -> Mehari.Response.text "Hello from Mehari")

As handlers take a Mehari.request in parameter we can operate on them. Here we retrieve the URL of the client's request and return it:

(fun req -> Mehari.Request.uri req |> Uri.to_string |> Mehari.Response.text)

See Request section to consult all client request related functions.

Status

Mehari provides its own representation of status codes as described in the gemini specification. Take a look at the signature of Mehari.Response.respond:

val respond : 'a status -> 'a -> response

Furthermore, the status input and success are defined as follows:

val input : string status
val success : Body.t -> Mime.t status

The inhabitant type of Mehari.Status.t carries the information of what is necessary for the creation of an associated response. In the case of an input response, a string is needed:

let input_resp =
  Mehari.(Response.respond Status.input) "Enter a message"

In the same way, a Mehari.Body.t and a Mehari.Mime.t are required to make a successful response:

open Mehari

let successful_resp =
  let body = Body.string "A successful response" in
  Response.respond (Status.success body) (Mime.gemini ())

See Response status for the complete list of status. Other functions described in Response section are mostly convenient functions built on top of Mehari.Response.respond.

Body

Successful responses are accompanied by a Mehari.Body.t. They are many methods to create a body, for example from a string:

let body = Mehari.Body.string "A response body"

Or from a Gemtext object:

let body =
  let open Mehari in
  Response.gemtext
    Gemtext.[
      heading `H1 "Thought on Gemtext markup";
      list_item "Date: February 2021";
      list_item "Tags: gemini, reviews";
      newline;
      heading `H2 "Introduction";
      newline;
      quote "The format permits richer typographic possibilities than the plain text of Gopher, but remains extremely easy to parse.";
      text "Here is an example of a Python parser that demonstrates the truth of that statement:";
      preformat "..." ~alt:"python"
    ]

Which is rendered as the following Gemtext document:

# Thought on Gemtext markup
* Date: February 2021
* Tags: gemini, reviews

## Introduction

> The format permits richer typographic possibilities than the plain text of Gopher, but remains extremely easy to parse.
Here is an example of a Python parser that demonstrates the truth of that statement:
```python
...
```
Data stream response

Mehari offers ways to keep client connections open forever and stream data in real time. Be sure to read this quick warning about this approach: Mehari.Response.Body.note-on-data-stream-response.

Mime

Mehari.Mime.t describes how the response body must be interpreted by the client. You can build your own mime with Mehari.Mime.make and specify the data encoding with the parameter charset:

let mp3 = Mehari.Mime.make "audio/mp3"

Some common MIME type are predefined. See Mime section.

The text/gemini MIME type allows an additional parameter lang to specify the languages used in the document according to the Gemini specification:

let french_ascii_gemini = Mehari.Mime.gemini ~charset:"ascii" ~lang:["fr"] ()
Inference

Mehari.Mime.from_filename enables MIME type infering from a filename.

Mehari also provides an experimental Conan integration via Mehari.Mime.from_content to infer MIME type from a string.

Routing

Obviously, the path of a route corresponds to the "path" component of the url requested by the client. :

Mehari.(Router.route Path.(~/"var"/"gemini") (fun _ -> ...))

In the following snippet, we construct a path to group all URL of form "/articles/xxx":

Mehari.(Router.route Path.(~/"articles" /: string) (fun article req ->
  Response.text (Printf.sprintf "Get article %S" article)))

Each path variable used is passed to the handler, this allows type safe routing. Predefined path variable are provided for all common standard data type and it is possible to define path variable for your own type with Variables. See the full documentation of Mehari.Path for more information.

It is the purpose of Mehari.Router.router to group routes together to produce a bigger handler:

let router =
  let open Mehari in
  Router.router [
    Router.route Path.root index_handler;
    Router.route Path.(~/"gemlog") gemlog_handler;
  ]

Advanced routing

Middleware

Mehari.Middleware.t allows to run code before and after the execution of another handler and produces a “bigger” Mehari.handler.

This example of an incrementable counter shows how to use them:

let counter = ref 0

let incr_count handler req =
  incr counter;
  handler req

let router =
  let open Mehari in
  Router.router [
      Router.route Path.root (fun _ ->
        Response.text (Printf.sprintf "Value %i" !counter));
      Router.route Path.(~/"incr") ~middlewares:[incr_count] (fun _ ->
          Response.respond Status.redirect_temp "/");
    ]

Rate limit

This route is limited to 3 accesses every 5 minutes:

open Mehari

let limit = Rate_limit.make ~period:3 5 `Minute

let limited_route = Router.route Path.(~/"stats") ~rate_limit:limit (fun req -> ...)

They are described in depth in section Rate limit.

Hosting

By default, the server runs on port 1965.

Use the openssl utility to generate a certificate and its associated private key (cert.pem and key.pem) for the domain name localhost:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 365 -nodes --subj "/CN=localhost"

Here is what you have to do to start the server using Mehari_miou:

let load_certs ~cert ~priv_key =
  let certs =
    let pem = In_channel.(with_open_text cert input_all) in
    match X509.Certificate.decode_pem_multiple pem with
    | Ok cs -> cs
    | Error (`Msg m) -> invalid_arg ("failed to parse certificates " ^ m)
  and priv_key =
    let pem = In_channel.(with_open_text priv_key input_all) in
    match X509.Private_key.decode_pem pem with
    | Ok key -> key
    | Error (`Msg m) -> invalid_arg ("failed to parse private key " ^ m)
  in
  [ (certs, priv_key) ]

let () =
  Miou_unix.run @@ fun () ->
  Mirage_crypto_rng_unix.use_default ();
  let certs = load_certs ~cert:"cert.pem" ~priv_key:"key.pem" in
  let ip = Ipaddr.(V4 (V4.Prefix.make 8 V4.localhost)) in
  Mehari_miou.run ~certs ip router

Virtual hosting

Mehari supports virtual hosting using "server name indication" (TLS SNI extension). Mehari.Router.virtual_host takes a list composed of a couple which represent a domain and his associated handler and produces a "biggest" Mehari.handler.