Skip to main content David Edelstein's Blog

🦙
🦙

Use Suave.IO to proxy to another server

Published: 2014-07-18
dave@edelsteinautomotive.com
David Edelstein
let build_proxy_resolver (fwd_to_host : String) fwd_to_port = 
  let heserver = System.Net.Dns.GetHostEntry(fwd_to_host)
  let ipaddr = heserver.AddressList.[0]
  fun (request : HttpRequest) ->
    Some (ipaddr, fwd_to_port)

let build_headers ctx =
  //add and remove headers from the ctx, return the header list
  ctx.request.headers

let proxy_app (ctx:HttpContext) = 
  let new_headers = build_headers ctx
  let fwd_ctx = {ctx with request={ctx.request with headers=new_headers}}
  let pxy = proxy (build_proxy_resolver "PROXY_TO.com" 80us) fwd_ctx
  {ctx with response = { ctx.response with status=Suave.Types.Codes.HTTP_200; content=SocketTask pxy }} |> Some

To use in an actual application, proxy_app can be inserted directly into the routing chain >>=

build_headers should be extended to add authorization headers or rewrite the host header as necessary. Also, build_proxy_resolver should only be called once so the IP lookup can be cached.

I plan on using something like this to serve as a reverse proxy to couchdb and then do my own security model in F# and Suave.