Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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)))
|> Dictionary<string, StringValues>

match ModelParser.tryParse<'T> None routeData with
| Ok model -> handler model next ctx
| Error _ -> skipPipeline

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
52 changes: 52 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,54 @@ 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.
[<InlineData("/p/John/Doe/9111222333", HttpStatusCode.UnprocessableEntity, "")>]
[<InlineData("/p/John/Doe/not-a-number", HttpStatusCode.UnprocessableEntity, "")>]
[<InlineData("/p/John/Doe//", HttpStatusCode.NotFound, "Not Found")>]
let ``routebind: GET "/p/{Name.First}/{Name.Last}/{Age}" returns person object``
(path: string, expectedStatus: HttpStatusCode, expectedContent: string)
=
task {
let endpoints: Endpoint list =
[
GET [
routeBindWithExtensions<Person>
(fun eb -> eb.WithOrder 1)
"/p/{Name.First}/{Name.Last}/{Age}"
(fun (person: Person) ->
text ($"Name.First: {person.Name.First}, Name.Last: {person.Name.Last}, Age: {person.Age}")
)
routefWithExtensions
(fun eb -> eb.WithOrder 2)
"/p/%s:firstName/%s:lastName/%d:age"
(fun (firstName: string, lastName: string, age: int64) ->
text ($"firstName: {firstName}, lastName: {lastName}, age: {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
}