Skip to content

How do I use Giraffe instead of Saturn?

Saturn is a functional alternative to MVC and Razor which sits on top of Giraffe. Giraffe itself is a functional wrapper around the ASP.NET Core web framework, making it easier to work with when using F#.

Since Saturn is built on top of Giraffe, migrating to using "raw" Giraffe is relatively simple to do.

Bootstrapping the Application

1. Open libraries

Navigate to the Server module in the Server project.

Remove

open Saturn
and replace it with
open Giraffe
open Microsoft.AspNetCore.Builder
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Hosting
open Microsoft.AspNetCore.Hosting

2. Replace application

In the same module, we need to replace the Server's application computation expression with some functions which set up the default host, configure the application and register services.

Remove this

let app =
    application {
        // ...setup functions
    }

run app

and replace it with this

let configureApp (app : IApplicationBuilder) =
    app
        .UseStaticFiles()
        .UseGiraffe webApp

let configureServices (services : IServiceCollection) =
    services
        .AddGiraffe() |> ignore


Host.CreateDefaultBuilder()
    .ConfigureWebHostDefaults(
        fun webHostBuilder ->
            webHostBuilder
                .Configure(configureApp)
                .ConfigureServices(configureServices)
                .UseUrls([|"http://0.0.0.0:8085"|])
                .UseWebRoot("public")
                |> ignore)
    .Build()
    .Run()

Routing

If you are using the standard SAFE template, there is nothing more you need to do, as routing is taken care of by Fable Remoting.

If however you are using the minimal template, you will need to replace the Saturn router expression with the Giraffe equivalent.

Replace this

let webApp =
    router {
        get Route.hello (json "Hello from SAFE!")
    }

with this

let webApp = route Route.hello >=> json "Hello from SAFE!"

Other setup

The steps shown here are the minimal necessary to get a SAFE app running using Giraffe.

As with any Server setup however, there are many more optional parameters that you may wish to configure, such as caching, response compression and serialisation options as seen in the default SAFE templates amongst many others.

See the Giraffe and ASP.NET Core host builder, application builder and service collection docs for more information on this.