SaturnFramework / Saturn

Opinionated, web development framework for F# which implements the server-side, functional MVC pattern
https://saturnframework.org
MIT License
707 stars 108 forks source link

Cache-Control for static files #271

Open BennieCopeland opened 3 years ago

BennieCopeland commented 3 years ago

Setting the Cache-Control header for static files is a pretty common thing to do, but there is no option when using use_static to set it. I worked around this using the following code, but it also requires me to duplicate setting the web root path. Is there a better way to do this out of the box?

type CacheControl =
    | NoCacheControl
    | CacheControl of string

let useStaticFiles cache (app : IApplicationBuilder) =
    match cache with
    | NoCacheControl ->
        app.UseStaticFiles()
    | CacheControl value ->
        let handler (ctx : StaticFileResponseContext) =
            ctx.Context.Response.Headers.Append("Cache-Control", StringValues(value))
            |> ignore

        let action = System.Action<StaticFileResponseContext>(handler)

        app.UseStaticFiles(StaticFileOptions(OnPrepareResponse = action))

let setWebRootPath path (builder : IWebHostBuilder) =
    let p = Path.Combine(Directory.GetCurrentDirectory(), path)
    builder.UseWebRoot(p)

let app = application {
    use_router Router.appRouter
    app_config (useStaticFiles (CacheControl "public, max-age=604800"))
    webhost_config (setWebRootPath "static")
    memory_cache
}
Krzysztof-Cieslak commented 3 years ago

Yes, currently use_static doesn't support any additional options. We should look into adding additional overload here that will enable customizations of it.