Bind only to localhost in Cohttp_lwt_unix?

My code seems to bind to 0.0.0.0 - is there a way to specify I only want to bind to localhost/127.0.0.1?

C.Server.create mode::(TCP (Port 8082)) (C.Server.make callback::server ()) |> Lwt_main.run

There is a ticket open asking for a way to make this easier which also includes one potential solution:

https://github.com/mirage/ocaml-cohttp/issues/543

EDIT: Including the code inline for future readers.

let%lwt ctx = Conduit_lwt_unix.init ~src:"127.0.0.1" () in
let ctx = Cohttp_lwt_unix.Client.custom_ctx ~ctx () in
Server.create ~ctx ~mode:(`TCP (`Port 8080))

In short, you create a custom conduit context which listens on a specific interface/address and use that context with your cohttp server.

1 Like

Yes, creating a custom conduit is the way to do this right now as @hcarty shows above. It’s on my list to simplify in Cohttp as soon as we get Cohttp 1.0 out of the door.

The reason for using Conduit like this is that it’s a point of abstraction for launch services – so another backend (e.g. the Conduit launchd one) can be used to trigger Cohttp requests from macOS launchd. However, the common case of just binding to a Unix port is too complex with this low-level API at present.

1 Like