SaturnFramework / Saturn

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

Router should allow handling HEAD requests #269

Open rmunn opened 3 years ago

rmunn commented 3 years ago

Currently the router { } CE has no way to allow a HEAD request to be handled. A HEAD request is supposed to return the headers, but not the body, that would have been produced by a GET request. I suggest adding two (well, four) more CE custom operations to the router { } CE:

The alternative is to do something kind of ugly like the following:

let head (handler : string -> HttpHandler) (next : HttpFunc) (ctx : HttpContext) =
    if HttpMethods.IsHead ctx.Request.Method then
        routef "/%s" handler next ctx
    else
        next ctx

let itemRouter = router {
    pipe_through (head ItemController.itemExists)
    get     "/" ItemController.getAllItems
    post    "/" ItemController.createItem
    getf    "/%s" ItemController.getSingleItem
    patchf  "/%s" ItemController.patchItem
    deletef "/%s" ItemController.archiveItem
}

let appRoot = router {
    forward "/api/items" (itemRouter true)
    // ...
}

(ItemController implementations omitted for brevity and because frankly, they're pretty obvious). Instead of pipe_through (head ItemController.itemExists), I'd like to be able to do headf "/%s" Controller.itemExists in my itemRouter, or else get_headf "/%s" ItemController.getSingleItem if the cost of building the response body for a single item isn't too great.

P.S. Although I've chosen not to use the Saturn controller CE in my application, it would be nice for the controller CE to also grow an exists operation to handle HEAD requests, and to have its show operation default to handling either GET or HEAD requests.

Krzysztof-Cieslak commented 3 years ago

Yes, this definitely makes sense, we should add it.

rmunn commented 3 years ago

PR #273 is an initial implementation. I would welcome feedback on it; see the PR description for the specific items I want to discuss.