Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion DOCUMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -1175,7 +1175,7 @@ let webApp =
]
```

The `routeBind<'T>` http handler can also contain valid `Regex` code to match a variety of different routes.
The `routeBind<'T>` http handler from the `Giraffe.Routing` module can also contain valid `Regex` code to match a variety of different routes.

For example by definition (according to the spec) a route with a trailing slash **is not** the same as the equivalent route without a trailing slash. Therefore it is perfectly valid if a web server doesn't serve (or serves a different response) for the following two routes:

Expand Down Expand Up @@ -1214,6 +1214,8 @@ routeBind<Blah> "/p/{foo}/{bar}(/*)" blahHandler

For a complete list of valid `Regex` codes please visit the official [Regular Expression Language Reference](https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference).

In case you are using `Giraffe.EndpointRouting`, the request path is handled by ASP.NET Core’s Endpoint Routing infrastructure. We therefore recommend reviewing the following sections of the official documentation: [url matching](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-10.0#url-matching) and [route constraints](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-10.0#route-constraints).

#### routeStartsWith

Sometimes it can be useful to pre-filter a route in order to enable certain functionality which should only be applied to a specific collection of routes.
Expand Down
26 changes: 26 additions & 0 deletions src/Giraffe/EndpointRouting.fs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ module private RequestDelegateBuilder =

[<AutoOpen>]
module Routers =
open System.Collections.Generic
open Microsoft.Extensions.Primitives

type HttpVerb =
| GET
Expand Down Expand Up @@ -274,6 +276,30 @@ module Routers =
let routef (path: PrintfFormat<_, _, _, _, 'T>) (routeHandler: 'T -> HttpHandler) : Endpoint =
routefWithExtensions (id) (path) (routeHandler)

let routeBindWithExtensions<'T>
(configureEndpoint: ConfigureEndpoint)
(path: string)
(routeHandler: 'T -> HttpHandler)
: Endpoint =

let bindRouteHandler (handler: 'T -> HttpHandler) : HttpHandler =
fun next ctx ->
let routeData =
ctx.GetRouteData().Values
|> Seq.map (fun kvp -> KeyValuePair(kvp.Key, StringValues(kvp.Value :?> string)))
|> fun kvps -> Dictionary<string, StringValues>(kvps) :> IDictionary<string, StringValues>
Comment thread
AugustoRengel marked this conversation as resolved.
Outdated

match ModelParser.tryParse<'T> None routeData with
| Ok model -> handler model next ctx
| Error _ -> RequestErrors.BAD_REQUEST "Failed to bind route parameters" next ctx

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps it's better to not return this RequestErrors.BAD_REQUEST "Failed to bind route parameters" message if the parse operation fails.

Instead, we need to just keep going, testing other routes, and eventually using the error handler specified by the client.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I replaced the error with skipPipeline, which allows the request to flow to the next handler, but it does not switch to another endpoint because the model parsing happens after endpoint selection.

To achieve the desired behavior, the model parsing would need to run before the endpoint selection phase. Based on the ASP.NET Core routing pipeline, this seems only possible by using a custom MatcherPolicy.

If there is any alternative or recommended approach to achieve this, please let me know if I am missing something.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just thinking out loud.

Something we do in other places of the project is to let our clients define a special error handler.

For example: #691.

Perhaps it makes sense to use this approach here.

Anyway, we can add this optional error handler later.


let newHandler = (bindRouteHandler routeHandler)

SimpleEndpoint(HttpVerb.NotSpecified, path, newHandler, configureEndpoint)

let routeBind<'T> (path: string) (routeHandler: 'T -> HttpHandler) : Endpoint =
routeBindWithExtensions<'T> (id) (path) (routeHandler)

let subRouteWithExtensions
(configureEndpoint: ConfigureEndpoint)
(path: string)
Expand Down
42 changes: 42 additions & 0 deletions tests/Giraffe.Tests/EndpointRoutingTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ open Xunit
open Giraffe
open Giraffe.EndpointRouting
open System.Net.Http
open System.Net

// ---------------------------------
// routef Tests
Expand Down Expand Up @@ -253,3 +254,44 @@ let ``routef: GET "/foo/%i:fooId/bar/%i/baz/%s" returns named and unnamed parame
let! content = response |> readText
content |> shouldEqual expected
}

[<CLIMutable>]
type Name = { First: string; Last: string }

[<CLIMutable>]
type Person = { Name: Name; Age: int }

[<Theory>]
[<InlineData("/p/John/Doe/32", HttpStatusCode.OK, "Name.First: John, Name.Last: Doe, Age: 32")>]
[<InlineData("/p/John%20Paul/Doe/32", HttpStatusCode.OK, "Name.First: John Paul, Name.Last: Doe, Age: 32")>]
[<InlineData("/p/John%20Paul/Doe/32/", HttpStatusCode.OK, "Name.First: John Paul, Name.Last: Doe, Age: 32")>]
Comment thread
64J0 marked this conversation as resolved.
let ``routebind: GET "/p/{Name.First}/{Name.Last}/{Age}" returns person object``
(path: string, expectedStatus: HttpStatusCode, expectedContent: string)
=
task {
let endpoints: Endpoint list =
[
GET [
routeBind<Person>
"/p/{Name.First}/{Name.Last}/{Age}"
(fun (person: Person) ->
text ($"Name.First: {person.Name.First}, Name.Last: {person.Name.Last}, Age: {person.Age}")
)
]
]

let notFoundHandler = "Not Found" |> text |> RequestErrors.notFound

let configureApp (app: IApplicationBuilder) =
app.UseRouting().UseGiraffe(endpoints).UseGiraffe(notFoundHandler)

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

let request = createRequest HttpMethod.Get path

let! response = makeRequest (fun () -> configureApp) configureServices () request
let! content = response |> isStatus expectedStatus |> readText

content |> shouldEqual expectedContent
}