giraffe-fsharp / Giraffe

A native functional ASP.NET Core web framework for F# developers.

Home Page:https://giraffe.wiki

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mapping a default endpoint route

JordanMarr opened this issue · comments

Pre-endpoint routes, I could specify a default / fallback route like this:

    let routes =     
        choose [ 
            GET >=> routeCi "/api/ping" >=> text "pong"
            GET >=> htmlFile "wwwroot/index.html"            // Default
        ]

How can I achieve the same with the Giraffe.EndpointRouting?

This seems to work:

let endpoints = 
    GET [
        route "/api/ping" (text "pong")
        route "" (htmlFile "wwwroot/index.html")
    ]

Can anyone confirm if this is the correct approach?

Yeah with the routlist being a somewhat flattened set of routes, your thought process is correct, though usually it's more customary to make the last endpoint the same as the root endpoint "/", with anything not matching that falling to a 404 handler: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-6.0#routing-basics

Really the only thing I'd say is to swap "" for "/"

With an example enpoint list like:

let handler1 : HttpHandler =
    fun (_ : HttpFunc) (ctx : HttpContext) ->
        ctx.WriteTextAsync "Hello World"

let endpoints = [
    GET [
        route "/h1" handler1
        route "/api/ping" (text "pong")
        route "/" (text "root") ]]

The following requests and responses occur (note that both base routes evaluate the same, and the empty 404 response for the unmatched route):

➜ curl localhost:5000/h1
Hello World                                                                                                                                     
➜ curl localhost:5000/api/ping
pong
➜ curl localhost:5000/        
root
➜ curl localhost:5000 
root
➜ curl localhost:5000/someunknown

➜ curl -v localhost:5000/someunknown
*   Trying 127.0.0.1:5000...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> GET /someunknown HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.81.0
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 404 Not Found
< Content-Length: 0
< Date: Wed, 06 Jul 2022 21:04:13 GMT
< Server: Kestrel
< 
* Connection #0 to host localhost left intact

Thank you very much for the response! It was very helpful.