Search code examples
f#suave

WebPart for forwarding requests to another server using Suave?


I would like to create a WebPart that forwards all requests to another web server that I specify.

Usage might look like this:

let app = 
  choose
    [
      path "/" >=> OK "Hello, world. "
      path "/graphql" >=> createProxy "localhost:5000"
      RequestErrors.NOT_FOUND "Not found"
    ]

startWebServer defaultConfig app

How should I implement this in Suave?


I found this snippet, but it seems to be for an old version of Suave:

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

Solution

  • This has now been added to Suave:

    open System
    open Suave
    open Suave.Proxy
    
    let app = 
      choose
        [
          path "/" >=> OK "Hello, world. "
          path "/graphql" >=> proxy (Uri "http://localhost:5000")
          RequestErrors.NOT_FOUND "Not found"
        ]
    
    startWebServer defaultConfig app